@wonderwhy-er/desktop-commander 0.3.4-alpha.0 → 0.3.5-alpha.0
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.
- package/dist/remote-device/mqtt/mqtt-transport.d.ts +6 -5
- package/dist/remote-device/mqtt/mqtt-transport.js +35 -37
- package/dist/remote-device/remote-channel.d.ts +12 -1
- package/dist/remote-device/remote-channel.js +115 -20
- package/dist/remote-device/transport-telemetry.d.ts +4 -1
- package/dist/remote-device/transport-telemetry.js +1 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -26,17 +26,18 @@ export declare class MqttTransport {
|
|
|
26
26
|
private readonly onDoorbell;
|
|
27
27
|
private readonly onReady;
|
|
28
28
|
private readonly onMalformed;
|
|
29
|
+
/** Called when the receiver stops itself after start() resolved, so RemoteChannel can restart MQTT. */
|
|
30
|
+
private readonly onFailed;
|
|
29
31
|
private client;
|
|
30
32
|
private stopped;
|
|
31
33
|
private ready;
|
|
32
34
|
private cancelStart;
|
|
33
35
|
private readonly topic;
|
|
34
36
|
/** Bind verified registration identity and RemoteChannel's delivery/readiness callbacks once. */
|
|
35
|
-
constructor(config: MqttConfig, userId: string, deviceId: string, onDoorbell: (payload: MqttDoorbell) => Promise<void>, onReady: (ready: boolean) => Promise<void>, onMalformed?: () => void
|
|
36
|
-
/**
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
*/
|
|
37
|
+
constructor(config: MqttConfig, userId: string, deviceId: string, onDoorbell: (payload: MqttDoorbell) => Promise<void>, onReady: (ready: boolean) => Promise<void>, onMalformed?: () => void,
|
|
38
|
+
/** Called when the receiver stops itself after start() resolved, so RemoteChannel can restart MQTT. */
|
|
39
|
+
onFailed?: () => void);
|
|
40
|
+
/** Make one connection attempt and resolve after QoS 1 SUBACK and the readiness update. */
|
|
40
41
|
start(): Promise<void>;
|
|
41
42
|
/** Publish one bounded result attempt without queuing it for a later connection. */
|
|
42
43
|
publishResult(callId: string, originInstance: string): Promise<void>;
|
|
@@ -30,8 +30,6 @@ export function createMqttConfig(credentials) {
|
|
|
30
30
|
clean: true,
|
|
31
31
|
keepalive: 30,
|
|
32
32
|
connectTimeout: CONNECT_TIMEOUT_MS,
|
|
33
|
-
// Spread reconnects between connector processes after a shared network outage.
|
|
34
|
-
reconnectPeriod: 1000 + Math.floor(Math.random() * 1500),
|
|
35
33
|
resubscribe: false,
|
|
36
34
|
queueQoSZero: false,
|
|
37
35
|
cert: credentials.cert,
|
|
@@ -49,23 +47,23 @@ export function mqttDoorbellTopic(userId, deviceId) {
|
|
|
49
47
|
/** A per-device subscription that validates and observes shadow notifications. */
|
|
50
48
|
export class MqttTransport {
|
|
51
49
|
/** Bind verified registration identity and RemoteChannel's delivery/readiness callbacks once. */
|
|
52
|
-
constructor(config, userId, deviceId, onDoorbell, onReady, onMalformed = () => { }
|
|
50
|
+
constructor(config, userId, deviceId, onDoorbell, onReady, onMalformed = () => { },
|
|
51
|
+
/** Called when the receiver stops itself after start() resolved, so RemoteChannel can restart MQTT. */
|
|
52
|
+
onFailed = () => { }) {
|
|
53
53
|
this.config = config;
|
|
54
54
|
this.userId = userId;
|
|
55
55
|
this.deviceId = deviceId;
|
|
56
56
|
this.onDoorbell = onDoorbell;
|
|
57
57
|
this.onReady = onReady;
|
|
58
58
|
this.onMalformed = onMalformed;
|
|
59
|
+
this.onFailed = onFailed;
|
|
59
60
|
this.client = null;
|
|
60
61
|
this.stopped = false;
|
|
61
62
|
this.ready = false;
|
|
62
63
|
this.cancelStart = null;
|
|
63
64
|
this.topic = mqttDoorbellTopic(userId, deviceId);
|
|
64
65
|
}
|
|
65
|
-
/**
|
|
66
|
-
* Connect once and resolve after QoS 1 SUBACK plus the readiness callback.
|
|
67
|
-
* MQTT.js owns socket reconnects; this receiver owns resubscription and admission.
|
|
68
|
-
*/
|
|
66
|
+
/** Make one connection attempt and resolve after QoS 1 SUBACK and the readiness update. */
|
|
69
67
|
async start() {
|
|
70
68
|
if (this.client || this.stopped) {
|
|
71
69
|
throw new Error("MQTT receiver already started or stopped");
|
|
@@ -74,12 +72,13 @@ export class MqttTransport {
|
|
|
74
72
|
console.debug("[MQTT] Connecting to broker:", new URL(this.config.url).hostname);
|
|
75
73
|
const client = connect(this.config.url, {
|
|
76
74
|
...this.config.options,
|
|
75
|
+
reconnectPeriod: 0, // MQTT.js IClientOptions.reconnectPeriod: 0 ms disables automatic retries. RemoteChannel schedules them.
|
|
77
76
|
// Stable identity also lets an AWS policy restrict this certificate's Connect permission.
|
|
78
77
|
clientId: `dc-device-${this.deviceId}`,
|
|
79
78
|
});
|
|
80
79
|
this.client = client;
|
|
81
|
-
//
|
|
82
|
-
//
|
|
80
|
+
// Each result publish in flight adds a "close" and a "packetsend" listener, so 140 allows about
|
|
81
|
+
// 70 at once. Passing it only prints Node's MaxListeners warning; no message is dropped.
|
|
83
82
|
client.setMaxListeners(140);
|
|
84
83
|
await new Promise((resolve, reject) => {
|
|
85
84
|
let settled = false;
|
|
@@ -98,17 +97,24 @@ export class MqttTransport {
|
|
|
98
97
|
resolve();
|
|
99
98
|
}
|
|
100
99
|
};
|
|
101
|
-
//
|
|
102
|
-
const
|
|
103
|
-
|
|
100
|
+
// Report a startup failure through start(), and a later disconnect through onFailed().
|
|
101
|
+
const stopWithError = (error) => {
|
|
102
|
+
if (this.stopped)
|
|
103
|
+
return;
|
|
104
|
+
const alreadyStarted = settled;
|
|
105
|
+
finish(error);
|
|
104
106
|
void this.stop().catch(() => { });
|
|
105
|
-
|
|
107
|
+
if (alreadyStarted)
|
|
108
|
+
this.onFailed();
|
|
109
|
+
};
|
|
110
|
+
// A connected socket without a granted subscription must not hang device startup.
|
|
111
|
+
const timer = setTimeout(() => stopWithError(new Error("MQTT connection/subscription timed out")), this.config.options.connectTimeout ?? CONNECT_TIMEOUT_MS);
|
|
106
112
|
this.cancelStart = () => finish(new Error("MQTT receiver stopped"));
|
|
107
|
-
client.
|
|
113
|
+
client.once("connect", () => {
|
|
108
114
|
if (this.stopped) {
|
|
109
115
|
return;
|
|
110
116
|
}
|
|
111
|
-
//
|
|
117
|
+
// A TCP connection alone cannot receive commands.
|
|
112
118
|
client.subscribe(this.topic, { qos: 1 }, (error, granted) => {
|
|
113
119
|
if (this.stopped || !client.connected) {
|
|
114
120
|
return;
|
|
@@ -117,8 +123,7 @@ export class MqttTransport {
|
|
|
117
123
|
granted?.length !== 1 ||
|
|
118
124
|
granted[0].topic !== this.topic ||
|
|
119
125
|
granted[0].qos !== 1) {
|
|
120
|
-
|
|
121
|
-
void this.stop().catch(() => { });
|
|
126
|
+
stopWithError(new Error("MQTT device subscription refused"));
|
|
122
127
|
return;
|
|
123
128
|
}
|
|
124
129
|
// Reject downgraded/foreign grants above, then let RemoteChannel persist capability.
|
|
@@ -128,27 +133,15 @@ export class MqttTransport {
|
|
|
128
133
|
.then(() => {
|
|
129
134
|
if (!this.stopped && this.ready) {
|
|
130
135
|
// Report usable command delivery only after the broker grants the subscription.
|
|
131
|
-
console.debug("[MQTT] Connected and subscribed;
|
|
136
|
+
console.debug("[MQTT] Connected and subscribed; receiving doorbells");
|
|
132
137
|
finish();
|
|
133
138
|
}
|
|
134
139
|
})
|
|
135
|
-
.catch(() =>
|
|
136
|
-
finish(new Error("MQTT readiness update failed"));
|
|
137
|
-
// should we stop??? we should restart connection
|
|
138
|
-
void this.stop().catch(() => { });
|
|
139
|
-
});
|
|
140
|
+
.catch(() => stopWithError(new Error("MQTT readiness update failed")));
|
|
140
141
|
});
|
|
141
142
|
});
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
if (this.ready && !this.stopped) {
|
|
145
|
-
console.debug("[MQTT] Disconnected; waiting for reconnection");
|
|
146
|
-
}
|
|
147
|
-
this.ready = false;
|
|
148
|
-
void this.onReady(this.ready).catch(() => { });
|
|
149
|
-
});
|
|
150
|
-
// MQTT.js reconnects after network faults. Never print TLS/broker errors,
|
|
151
|
-
// which can include certificate paths or broker-provided sensitive text.
|
|
143
|
+
client.once("close", () => stopWithError(new Error("MQTT connection closed")));
|
|
144
|
+
// Raw TLS/broker errors can include certificate paths or broker-provided sensitive text.
|
|
152
145
|
client.on("error", () => { });
|
|
153
146
|
// Treat broker input as untrusted before RemoteChannel performs any database read.
|
|
154
147
|
// Reject retained backlog and oversized data before parsing, then enforce exact identity.
|
|
@@ -170,7 +163,7 @@ export class MqttTransport {
|
|
|
170
163
|
}
|
|
171
164
|
let payload;
|
|
172
165
|
try {
|
|
173
|
-
//
|
|
166
|
+
// MQTT over TLS hands over whole packets, so a payload can't arrive in part; its shape is checked below.
|
|
174
167
|
payload = JSON.parse(bytes.toString("utf8"));
|
|
175
168
|
}
|
|
176
169
|
catch {
|
|
@@ -244,14 +237,19 @@ export class MqttTransport {
|
|
|
244
237
|
packet.payload === payload)
|
|
245
238
|
messageId = packet.messageId;
|
|
246
239
|
};
|
|
247
|
-
//
|
|
248
|
-
//
|
|
240
|
+
// A timeout settles only this publish: finish() removes its own listeners and outgoing
|
|
241
|
+
// message, and the connection stays up for the others.
|
|
249
242
|
const timer = setTimeout(() => finish(new Error("MQTT result acknowledgement timed out")), 5000);
|
|
250
243
|
client.once("close", onClose);
|
|
251
244
|
client.on("packetsend", onPacket);
|
|
252
245
|
try {
|
|
253
246
|
observeTransport({ stage: 'publish_from_device', callId, deviceId: this.deviceId, userId: this.userId, transport: 'mqtt' });
|
|
254
|
-
client.publish(topic, payload, { qos: 1, retain: false }, (error) =>
|
|
247
|
+
client.publish(topic, payload, { qos: 1, retain: false }, (error) => {
|
|
248
|
+
// MQTT.js can fail pending publishes during shutdown before their close listeners run.
|
|
249
|
+
if (error && (this.stopped || !client.connected))
|
|
250
|
+
return onClose();
|
|
251
|
+
finish(error ? new Error("MQTT result publish failed") : undefined);
|
|
252
|
+
});
|
|
255
253
|
}
|
|
256
254
|
catch {
|
|
257
255
|
finish(new Error("MQTT result publish failed"));
|
|
@@ -67,6 +67,8 @@ export declare class RemoteChannel {
|
|
|
67
67
|
private mqttLifecycle;
|
|
68
68
|
private removeMqttRolloutListener;
|
|
69
69
|
private authGeneration;
|
|
70
|
+
private mqttRestartTimer;
|
|
71
|
+
private mqttRestartFailures;
|
|
70
72
|
private deviceId;
|
|
71
73
|
private deviceName;
|
|
72
74
|
private onToolCall;
|
|
@@ -164,13 +166,20 @@ export declare class RemoteChannel {
|
|
|
164
166
|
}>;
|
|
165
167
|
registerDevice(capabilities: any, currentDeviceId: string | undefined, deviceName: string, onToolCall: (payload: any) => void): Promise<void>;
|
|
166
168
|
private updateMqttTransport;
|
|
169
|
+
/** Schedule the next connection attempt after a startup failure or a disconnected receiver. */
|
|
170
|
+
private scheduleMqttRestart;
|
|
167
171
|
private startMqtt;
|
|
168
172
|
private prepareMqttConfig;
|
|
169
173
|
private startMqttTransport;
|
|
174
|
+
/** The receiver has already stopped itself and withdrawn readiness before reporting the disconnect. */
|
|
175
|
+
private onMqttReceiverFailed;
|
|
176
|
+
private cancelMqttRestart;
|
|
170
177
|
private stopMqttTransport;
|
|
171
178
|
private setMqttReady;
|
|
172
|
-
/**
|
|
179
|
+
/** Transport and execution on: MQTT runs calls and Broadcast only observes. */
|
|
180
|
+
private isMqttExecutionEnabled;
|
|
173
181
|
private onMqttDoorbell;
|
|
182
|
+
private recoverAfterMqttChange;
|
|
174
183
|
private onBroadcastDoorbell;
|
|
175
184
|
/**
|
|
176
185
|
* Mark this join dispatchable by writing `status`. The write has to land —
|
|
@@ -265,6 +274,8 @@ export declare class RemoteChannel {
|
|
|
265
274
|
* and `status`.
|
|
266
275
|
*/
|
|
267
276
|
private isReachable;
|
|
277
|
+
/** Recovery requires the selected execution transport and the local executor to be ready. */
|
|
278
|
+
private canRunCalls;
|
|
268
279
|
/**
|
|
269
280
|
* Set `status` from actual reachability. `status` is transport-agnostic (the
|
|
270
281
|
* server filters on it), so it must not follow one channel's health — the
|
|
@@ -102,6 +102,9 @@ const SOCKET_SETTLE_POLL_MS = 20;
|
|
|
102
102
|
// scan so a pathological backlog cannot turn one reconnect into an unbounded
|
|
103
103
|
// burst of REST claims/tool executions.
|
|
104
104
|
const PENDING_RECOVERY_BATCH_SIZE = 100;
|
|
105
|
+
const MQTT_FAST_RETRY_LIMIT = 10; // Device retry policy counts retries after the initial connection attempt.
|
|
106
|
+
const MQTT_FAST_RETRY_DELAY_MS = 10000; // Wait 10 seconds after each failure during the first ten retries.
|
|
107
|
+
const MQTT_SLOW_RETRY_DELAY_MS = 5 * 60000; // After ten failed retries, wait five minutes between attempts.
|
|
105
108
|
function jitterAround(baseMs, random) {
|
|
106
109
|
const sample = Math.max(0, Math.min(1, random()));
|
|
107
110
|
return Math.max(1, Math.round(baseMs * (0.5 + sample)));
|
|
@@ -218,6 +221,8 @@ export class RemoteChannel {
|
|
|
218
221
|
this.mqttLifecycle = Promise.resolve();
|
|
219
222
|
this.removeMqttRolloutListener = null;
|
|
220
223
|
this.authGeneration = 0;
|
|
224
|
+
this.mqttRestartTimer = null;
|
|
225
|
+
this.mqttRestartFailures = 0;
|
|
221
226
|
// Store subscription parameters for channel recreation
|
|
222
227
|
this.deviceId = null;
|
|
223
228
|
this.deviceName = null;
|
|
@@ -384,6 +389,8 @@ export class RemoteChannel {
|
|
|
384
389
|
return;
|
|
385
390
|
this.handlingSignedOut = true;
|
|
386
391
|
this.authGeneration++;
|
|
392
|
+
// A retry for the old session must not block MQTT startup if session recovery succeeds.
|
|
393
|
+
this.cancelMqttRestart();
|
|
387
394
|
try {
|
|
388
395
|
const cached = this.lastKnownSession;
|
|
389
396
|
if (cached?.refresh_token && this.client) {
|
|
@@ -606,15 +613,47 @@ export class RemoteChannel {
|
|
|
606
613
|
this.mqttLifecycle = this.mqttLifecycle
|
|
607
614
|
.then(async () => {
|
|
608
615
|
if (enabled) {
|
|
616
|
+
// Registration or a session refresh can request a start while a retry is pending.
|
|
617
|
+
if (this.mqttRestartTimer)
|
|
618
|
+
return;
|
|
609
619
|
await this.startMqtt();
|
|
620
|
+
if (this.mqttReceiver && this.mqttRestartFailures > 0) {
|
|
621
|
+
captureRemote('remote_channel_mqtt_restart_succeeded', { attempts: this.mqttRestartFailures }).catch(() => { });
|
|
622
|
+
this.mqttRestartFailures = 0;
|
|
623
|
+
}
|
|
610
624
|
}
|
|
611
625
|
else {
|
|
626
|
+
this.mqttRestartFailures = 0;
|
|
612
627
|
await this.stopMqttTransport();
|
|
613
628
|
}
|
|
614
629
|
})
|
|
615
|
-
.catch(() =>
|
|
630
|
+
.catch((error) => {
|
|
631
|
+
console.debug('[MQTT] Transport unavailable; will try again:', error?.message);
|
|
632
|
+
this.scheduleMqttRestart();
|
|
633
|
+
});
|
|
616
634
|
return this.mqttLifecycle;
|
|
617
635
|
}
|
|
636
|
+
/** Schedule the next connection attempt after a startup failure or a disconnected receiver. */
|
|
637
|
+
scheduleMqttRestart() {
|
|
638
|
+
if (this.mqttRestartTimer || this.shuttingDown || this.sessionLost || this.handlingSignedOut)
|
|
639
|
+
return;
|
|
640
|
+
if (!rolloutManager.get('MQTT_TRANSPORT_ENABLED'))
|
|
641
|
+
return;
|
|
642
|
+
const generation = this.authGeneration;
|
|
643
|
+
this.mqttRestartFailures++;
|
|
644
|
+
const delayMs = this.mqttRestartFailures <= MQTT_FAST_RETRY_LIMIT
|
|
645
|
+
? MQTT_FAST_RETRY_DELAY_MS
|
|
646
|
+
: MQTT_SLOW_RETRY_DELAY_MS;
|
|
647
|
+
captureRemote('remote_channel_mqtt_restart_scheduled', { failures: this.mqttRestartFailures, delay_ms: delayMs }).catch(() => { });
|
|
648
|
+
this.mqttRestartTimer = setTimeout(() => {
|
|
649
|
+
this.mqttRestartTimer = null;
|
|
650
|
+
// The user signed out or in during the wait: skip, the new sign-in starts MQTT itself.
|
|
651
|
+
if (generation !== this.authGeneration)
|
|
652
|
+
return;
|
|
653
|
+
void this.updateMqttTransport(rolloutManager.get('MQTT_TRANSPORT_ENABLED'));
|
|
654
|
+
}, delayMs);
|
|
655
|
+
this.mqttRestartTimer.unref();
|
|
656
|
+
}
|
|
618
657
|
async startMqtt() {
|
|
619
658
|
if (!rolloutManager.get('MQTT_TRANSPORT_ENABLED')) {
|
|
620
659
|
console.debug('[DEBUG] MQTT transport DISABLED');
|
|
@@ -671,12 +710,33 @@ export class RemoteChannel {
|
|
|
671
710
|
return;
|
|
672
711
|
}
|
|
673
712
|
await this.setMqttReady(ready);
|
|
674
|
-
|
|
713
|
+
// Doorbells sent while MQTT was down are not delivered later, so look in the
|
|
714
|
+
// database for calls that are still waiting and run them.
|
|
715
|
+
if (ready)
|
|
716
|
+
this.recoverAfterMqttChange('after MQTT connected');
|
|
717
|
+
},
|
|
718
|
+
// A message was thrown away because it isn't a valid doorbell for this device.
|
|
719
|
+
// Log it so a rejected doorbell is visible in the device log.
|
|
720
|
+
() => console.debug('[MQTT] Doorbell rejected: not a valid doorbell for this device'), () => this.onMqttReceiverFailed(receiver));
|
|
675
721
|
this.mqttReceiver = receiver;
|
|
676
722
|
await receiver.start();
|
|
677
723
|
}
|
|
724
|
+
/** The receiver has already stopped itself and withdrawn readiness before reporting the disconnect. */
|
|
725
|
+
onMqttReceiverFailed(receiver) {
|
|
726
|
+
if (this.mqttReceiver !== receiver)
|
|
727
|
+
return;
|
|
728
|
+
console.debug('[MQTT] Receiver disconnected; scheduling a retry');
|
|
729
|
+
this.mqttReceiver = null;
|
|
730
|
+
this.scheduleMqttRestart();
|
|
731
|
+
}
|
|
732
|
+
cancelMqttRestart() {
|
|
733
|
+
if (this.mqttRestartTimer)
|
|
734
|
+
clearTimeout(this.mqttRestartTimer);
|
|
735
|
+
this.mqttRestartTimer = null;
|
|
736
|
+
}
|
|
678
737
|
async stopMqttTransport() {
|
|
679
738
|
console.debug('[DEBUG] stopping MQTT transport');
|
|
739
|
+
this.cancelMqttRestart();
|
|
680
740
|
const receiver = this.mqttReceiver;
|
|
681
741
|
this.mqttReceiver = null;
|
|
682
742
|
if (receiver) {
|
|
@@ -722,11 +782,24 @@ export class RemoteChannel {
|
|
|
722
782
|
throw new Error('MQTT capability could not be saved');
|
|
723
783
|
}
|
|
724
784
|
}
|
|
725
|
-
/**
|
|
785
|
+
/** Transport and execution on: MQTT runs calls and Broadcast only observes. */
|
|
786
|
+
isMqttExecutionEnabled() {
|
|
787
|
+
return rolloutManager.get('MQTT_TRANSPORT_ENABLED') && rolloutManager.get('MQTT_ON_DEVICE_EXECUTION_ENABLED');
|
|
788
|
+
}
|
|
726
789
|
async onMqttDoorbell(payload) {
|
|
727
790
|
if (this.shuttingDown || this.sessionLost || this.handlingSignedOut) {
|
|
728
791
|
return;
|
|
729
792
|
}
|
|
793
|
+
if (!this.isMqttExecutionEnabled()) {
|
|
794
|
+
console.debug(`[MQTT] Doorbell for call ${payload.call_id} observed only; execution is off`);
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
await this.onDoorbell(payload, 'mqtt');
|
|
798
|
+
}
|
|
799
|
+
recoverAfterMqttChange(reason) {
|
|
800
|
+
this.recoverPendingCalls(reason).catch((error) => {
|
|
801
|
+
console.error(`[DEBUG] Pending call recovery failed (${reason}):`, error?.message);
|
|
802
|
+
});
|
|
730
803
|
}
|
|
731
804
|
async onBroadcastDoorbell(payload) {
|
|
732
805
|
if (this.shuttingDown || this.sessionLost || this.handlingSignedOut) {
|
|
@@ -734,7 +807,11 @@ export class RemoteChannel {
|
|
|
734
807
|
}
|
|
735
808
|
observeTransport({ stage: 'received', payload, deviceId: this.deviceId,
|
|
736
809
|
userId: this.user?.id, transport: 'broadcast' });
|
|
737
|
-
|
|
810
|
+
if (this.isMqttExecutionEnabled()) {
|
|
811
|
+
console.debug(`[DEBUG] Broadcast doorbell for call ${payload?.call_id} observed only; MQTT runs calls`);
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
await this.onDoorbell(payload, 'broadcast');
|
|
738
815
|
}
|
|
739
816
|
/**
|
|
740
817
|
* Mark this join dispatchable by writing `status`. The write has to land —
|
|
@@ -889,7 +966,9 @@ export class RemoteChannel {
|
|
|
889
966
|
}
|
|
890
967
|
})
|
|
891
968
|
.on('broadcast', { event: 'new_call' }, ({ payload }) => {
|
|
892
|
-
|
|
969
|
+
console.debug(`[DEBUG] Received broadcast doorbell for call ${payload?.call_id}`);
|
|
970
|
+
this.onBroadcastDoorbell(payload)
|
|
971
|
+
.catch((e) => {
|
|
893
972
|
console.error('[DEBUG] Doorbell handling failed:', e?.message);
|
|
894
973
|
});
|
|
895
974
|
})
|
|
@@ -962,9 +1041,10 @@ export class RemoteChannel {
|
|
|
962
1041
|
* The follow-up onDoorbell() call performs the existing conditional claim,
|
|
963
1042
|
* which makes this safe against a doorbell arriving at the same time.
|
|
964
1043
|
*/
|
|
965
|
-
async recoverPendingCalls() {
|
|
966
|
-
if (!this.client || !this.deviceId || !this.
|
|
1044
|
+
async recoverPendingCalls(reason = 'after reconnect') {
|
|
1045
|
+
if (!this.client || !this.deviceId || !this.canRunCalls()) {
|
|
967
1046
|
return;
|
|
1047
|
+
}
|
|
968
1048
|
const { data: pending, error } = await this.client
|
|
969
1049
|
.from('mcp_remote_calls')
|
|
970
1050
|
.select('id,device_id')
|
|
@@ -980,7 +1060,7 @@ export class RemoteChannel {
|
|
|
980
1060
|
}
|
|
981
1061
|
if (!pending?.length)
|
|
982
1062
|
return;
|
|
983
|
-
console.log(`♻️ Recovering ${pending.length} pending remote call${pending.length === 1 ? '' : 's'}
|
|
1063
|
+
console.log(`♻️ Recovering ${pending.length} pending remote call${pending.length === 1 ? '' : 's'} ${reason}`);
|
|
984
1064
|
captureRemote('remote_channel_pending_recovery', {
|
|
985
1065
|
pending_count: pending.length,
|
|
986
1066
|
batch_capped: pending.length === PENDING_RECOVERY_BATCH_SIZE,
|
|
@@ -988,12 +1068,13 @@ export class RemoteChannel {
|
|
|
988
1068
|
// Claim quickly; dispatchToolCall() does not await tool execution, so
|
|
989
1069
|
// this loop serializes only the small REST claim operations.
|
|
990
1070
|
for (const row of pending) {
|
|
991
|
-
if (!this.
|
|
1071
|
+
if (!this.canRunCalls()) {
|
|
992
1072
|
break;
|
|
1073
|
+
}
|
|
993
1074
|
await this.onDoorbell({
|
|
994
1075
|
call_id: row.id,
|
|
995
1076
|
device_id: row.device_id,
|
|
996
|
-
});
|
|
1077
|
+
}, 'recovery');
|
|
997
1078
|
}
|
|
998
1079
|
}
|
|
999
1080
|
/** Hand a call to device.ts, observing the rejection — the handler is async
|
|
@@ -1016,22 +1097,25 @@ export class RemoteChannel {
|
|
|
1016
1097
|
* claims the row (pending -> executing) and returns it, and it is handed to
|
|
1017
1098
|
* device.ts marked as claimed.
|
|
1018
1099
|
*/
|
|
1019
|
-
async onDoorbell(payload) {
|
|
1020
|
-
if (this.shuttingDown || this.sessionLost || this.handlingSignedOut)
|
|
1100
|
+
async onDoorbell(payload, source = 'broadcast') {
|
|
1101
|
+
if (this.shuttingDown || this.sessionLost || this.handlingSignedOut) {
|
|
1021
1102
|
return;
|
|
1103
|
+
}
|
|
1022
1104
|
const generation = this.authGeneration;
|
|
1023
1105
|
const callId = payload?.call_id;
|
|
1024
|
-
if (!callId)
|
|
1106
|
+
if (!callId) {
|
|
1025
1107
|
return;
|
|
1108
|
+
}
|
|
1026
1109
|
if (payload?.device_id !== this.deviceId) {
|
|
1027
1110
|
console.debug('[DEBUG] Ignoring doorbell for different device');
|
|
1028
1111
|
return;
|
|
1029
1112
|
}
|
|
1030
1113
|
// Not a telemetry event on purpose: ~126k/day in prod. Transport usage
|
|
1031
1114
|
// is already segmentable server-side via metadata.transport.
|
|
1032
|
-
console.debug(
|
|
1033
|
-
if (!this.client)
|
|
1115
|
+
console.debug(`[DEBUG] Doorbell received for call: ${callId} (from ${source})`);
|
|
1116
|
+
if (!this.client) {
|
|
1034
1117
|
return;
|
|
1118
|
+
}
|
|
1035
1119
|
// Retry on transient failures (a REST blip while the socket stays
|
|
1036
1120
|
// healthy). This claim is the only way we learn about a call,
|
|
1037
1121
|
// so a hiccup must not cost a timeout. PostgREST interprets the
|
|
@@ -1064,6 +1148,8 @@ export class RemoteChannel {
|
|
|
1064
1148
|
if (generation !== this.authGeneration || this.shuttingDown || this.sessionLost || this.handlingSignedOut)
|
|
1065
1149
|
return;
|
|
1066
1150
|
if (row) {
|
|
1151
|
+
// Who ran the call: MQTT, Broadcast, or the scan for waiting calls.
|
|
1152
|
+
observeTransport({ stage: 'call_claimed', callId, deviceId: this.deviceId, userId: this.user?.id, claimedBy: source });
|
|
1067
1153
|
// The server writes the user's rollouts into every call row; a row
|
|
1068
1154
|
// without them (an older server) keeps what the device has.
|
|
1069
1155
|
rolloutManager.update(row.metadata?.rollouts);
|
|
@@ -1075,7 +1161,7 @@ export class RemoteChannel {
|
|
|
1075
1161
|
}
|
|
1076
1162
|
if (!claimError) {
|
|
1077
1163
|
// Claimed by a duplicate doorbell or another process, or cleaned up.
|
|
1078
|
-
console.debug('[DEBUG] Doorbell call already claimed or gone:', callId);
|
|
1164
|
+
console.debug('[DEBUG] Doorbell call already claimed or gone. No row found:', callId);
|
|
1079
1165
|
await captureRemote('remote_channel_doorbell_claim_no_row', { call_id: callId });
|
|
1080
1166
|
return;
|
|
1081
1167
|
}
|
|
@@ -1109,7 +1195,7 @@ export class RemoteChannel {
|
|
|
1109
1195
|
// the row carries no claimant. Running it on that guess executes a
|
|
1110
1196
|
// side-effecting tool twice; skipping costs one call its timeout, which
|
|
1111
1197
|
// is what a failed doorbell read already cost before the claim path.
|
|
1112
|
-
console.debug('[DEBUG] Doorbell call already claimed or gone:', callId);
|
|
1198
|
+
console.debug('[DEBUG] Doorbell call already claimed or gone. not executing:', callId);
|
|
1113
1199
|
await captureRemote('remote_channel_doorbell_claim_unresolved', {
|
|
1114
1200
|
call_id: callId,
|
|
1115
1201
|
status: current?.status ?? null,
|
|
@@ -1365,8 +1451,9 @@ export class RemoteChannel {
|
|
|
1365
1451
|
return claimed;
|
|
1366
1452
|
}
|
|
1367
1453
|
async updateCallResult(callId, status, result = null, errorMessage = null, originInstance) {
|
|
1368
|
-
if (!this.client)
|
|
1454
|
+
if (!this.client) {
|
|
1369
1455
|
throw new Error('Client not initialized');
|
|
1456
|
+
}
|
|
1370
1457
|
// The DB terminal-status trigger stamps completed_at using PostgreSQL
|
|
1371
1458
|
// time. Do not send a device-generated timestamp.
|
|
1372
1459
|
const updateData = { status };
|
|
@@ -1416,12 +1503,14 @@ export class RemoteChannel {
|
|
|
1416
1503
|
}
|
|
1417
1504
|
async publishMqttResult(callId, originInstance) {
|
|
1418
1505
|
const receiver = this.mqttReceiver;
|
|
1419
|
-
if (!receiver)
|
|
1506
|
+
if (!receiver) {
|
|
1420
1507
|
return;
|
|
1508
|
+
}
|
|
1421
1509
|
const generation = this.authGeneration;
|
|
1422
1510
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
1423
|
-
if (generation !== this.authGeneration || receiver !== this.mqttReceiver || this.shuttingDown || this.sessionLost)
|
|
1511
|
+
if (generation !== this.authGeneration || receiver !== this.mqttReceiver || this.shuttingDown || this.sessionLost) {
|
|
1424
1512
|
return;
|
|
1513
|
+
}
|
|
1425
1514
|
const observation = { callId, deviceId: this.deviceId, userId: this.user?.id, transport: 'mqtt' };
|
|
1426
1515
|
try {
|
|
1427
1516
|
await receiver.publishResult(callId, originInstance);
|
|
@@ -1447,6 +1536,12 @@ export class RemoteChannel {
|
|
|
1447
1536
|
&& this.channelReady
|
|
1448
1537
|
&& this.localExecutorProbe();
|
|
1449
1538
|
}
|
|
1539
|
+
/** Recovery requires the selected execution transport and the local executor to be ready. */
|
|
1540
|
+
canRunCalls() {
|
|
1541
|
+
return this.isMqttExecutionEnabled()
|
|
1542
|
+
? this.mqttReady && this.localExecutorProbe()
|
|
1543
|
+
: this.isReachable();
|
|
1544
|
+
}
|
|
1450
1545
|
/**
|
|
1451
1546
|
* Set `status` from actual reachability. `status` is transport-agnostic (the
|
|
1452
1547
|
* server filters on it), so it must not follow one channel's health — the
|
|
@@ -9,6 +9,8 @@ type TransportObservation = ({
|
|
|
9
9
|
toolName?: string;
|
|
10
10
|
operation?: string;
|
|
11
11
|
operationId?: string;
|
|
12
|
+
/** Who claimed the call (call_claimed): MQTT, Broadcast, or the scan for waiting calls. */
|
|
13
|
+
claimedBy?: 'mqtt' | 'broadcast' | 'recovery';
|
|
12
14
|
}) & {
|
|
13
15
|
userId: string | undefined;
|
|
14
16
|
transport?: 'broadcast' | 'mqtt';
|
|
@@ -19,12 +21,13 @@ export declare function observeTransport(input: TransportObservation): {
|
|
|
19
21
|
source_process_id: `${string}-${string}-${string}-${string}-${string}`;
|
|
20
22
|
schema_version: number;
|
|
21
23
|
timestamp_utc: string;
|
|
24
|
+
claimed_by?: "mqtt" | "broadcast" | "recovery" | undefined;
|
|
22
25
|
operation_id?: string | undefined;
|
|
23
26
|
operation?: string | undefined;
|
|
24
27
|
tool_name?: string | undefined;
|
|
25
28
|
notification_id?: string | undefined;
|
|
26
29
|
attempt_number?: number | undefined;
|
|
27
|
-
transport?: "
|
|
30
|
+
transport?: "mqtt" | "broadcast" | undefined;
|
|
28
31
|
call_id: string;
|
|
29
32
|
device_id: string;
|
|
30
33
|
stage: string;
|
|
@@ -36,6 +36,7 @@ export function observeTransport(input) {
|
|
|
36
36
|
input.toolName.length <= 128 ? { tool_name: input.toolName } : {}),
|
|
37
37
|
...(!receipt && typeof input.operation === 'string' && input.operation ? { operation: input.operation } : {}),
|
|
38
38
|
...(typeof operationId === 'string' && operationId ? { operation_id: operationId } : {}),
|
|
39
|
+
...(!receipt && input.claimedBy ? { claimed_by: input.claimedBy } : {}),
|
|
39
40
|
observation_id: observationId,
|
|
40
41
|
source_process_id: PROCESS_ID,
|
|
41
42
|
schema_version: 1,
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.3.
|
|
1
|
+
export declare const VERSION = "0.3.5-alpha.0";
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = '0.3.
|
|
1
|
+
export const VERSION = '0.3.5-alpha.0';
|
package/package.json
CHANGED