@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.
- package/README.md +35 -13
- package/dist/config-manager.d.ts +25 -35
- package/dist/config-manager.js +196 -95
- package/dist/npm-scripts/remote.js +35 -2
- package/dist/remote-device/desktop-commander-integration.d.ts +26 -0
- package/dist/remote-device/desktop-commander-integration.js +78 -4
- package/dist/remote-device/device.d.ts +10 -0
- package/dist/remote-device/device.js +95 -8
- package/dist/remote-device/remote-channel.d.ts +25 -17
- package/dist/remote-device/remote-channel.js +264 -77
- package/dist/server.js +6 -4
- package/dist/setup-claude-server.js +1 -1
- package/dist/terminal-manager.js +39 -0
- package/dist/tools/edit.js +13 -1
- package/dist/tools/process.d.ts +15 -1
- package/dist/tools/process.js +44 -13
- package/dist/uninstall-claude-server.js +0 -15
- package/dist/utils/files/text.d.ts +1 -0
- package/dist/utils/files/text.js +38 -8
- package/dist/utils/usageTracker.d.ts +0 -8
- package/dist/utils/usageTracker.js +52 -53
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +5 -4
- package/dist/utils/mcp-ui.d.ts +0 -7
- package/dist/utils/mcp-ui.js +0 -22
|
@@ -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
|
-
|
|
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 —
|
|
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
|
|
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' : '
|
|
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
|
|
520
|
-
//
|
|
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
|
|
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 =
|
|
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
|
-
|
|
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
|
|
721
|
-
//
|
|
722
|
-
//
|
|
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'
|
|
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
|
-
|
|
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 +
|
|
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
|
package/dist/server.js
CHANGED
|
@@ -1051,16 +1051,18 @@ server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
|
1051
1051
|
{
|
|
1052
1052
|
name: "get_recent_tool_calls",
|
|
1053
1053
|
description: `
|
|
1054
|
-
Get recent tool call history with
|
|
1055
|
-
Returns chronological list of
|
|
1054
|
+
Get recent local tool call history with arguments and outputs.
|
|
1055
|
+
Returns a chronological list of recent calls loaded from the local history file.
|
|
1056
1056
|
|
|
1057
1057
|
Useful for:
|
|
1058
1058
|
- Onboarding new chats about work already done
|
|
1059
1059
|
- Recovering context after chat history loss
|
|
1060
1060
|
- Debugging tool call sequences
|
|
1061
1061
|
|
|
1062
|
-
Note: Does not track its own calls or
|
|
1063
|
-
History
|
|
1062
|
+
Note: Does not track its own calls or track_ui_event.
|
|
1063
|
+
History is persisted locally in tool-history.jsonl, keeps up to the last 1000
|
|
1064
|
+
calls in memory, and trims older on-disk history. Stored outputs over 4 KiB
|
|
1065
|
+
are replaced with an omission marker.
|
|
1064
1066
|
|
|
1065
1067
|
${CMD_PREFIX_DESCRIPTION}`,
|
|
1066
1068
|
inputSchema: zodToJsonSchema(GetRecentToolCallsArgsSchema),
|
package/dist/terminal-manager.js
CHANGED
|
@@ -203,6 +203,28 @@ export class TerminalManager {
|
|
|
203
203
|
// Spawn the process with appropriate arguments
|
|
204
204
|
const childProcess = spawn(spawnConfig.executable, spawnConfig.args, spawnOptions);
|
|
205
205
|
let output = '';
|
|
206
|
+
// spawn() reports failure asynchronously via an 'error' event; it does not
|
|
207
|
+
// throw. Node rethrows an 'error' that has no listener as an uncaught
|
|
208
|
+
// exception, and our process-level handler (src/index.ts) turns that into
|
|
209
|
+
// process.exit(1). So an unresolvable executable — e.g. shell: "/usr/bin/bash"
|
|
210
|
+
// on Windows — used to kill the entire MCP server one tick AFTER this
|
|
211
|
+
// function had already returned "Failed to get process ID", making the crash
|
|
212
|
+
// look unrelated to the command that caused it. Under `remote` the parent
|
|
213
|
+
// then kept accepting tool calls over a dead stdio pipe ("Not connected").
|
|
214
|
+
//
|
|
215
|
+
// Attach before any return path below, and keep it for the session lifetime
|
|
216
|
+
// so a later runtime error (EPIPE on a closed stdin, ...) can't crash us either.
|
|
217
|
+
let forwardProcessError = null;
|
|
218
|
+
let pendingProcessError = null;
|
|
219
|
+
childProcess.on('error', (err) => {
|
|
220
|
+
if (forwardProcessError) {
|
|
221
|
+
forwardProcessError(err);
|
|
222
|
+
}
|
|
223
|
+
else {
|
|
224
|
+
pendingProcessError = err;
|
|
225
|
+
console.error(`Process error for "${command}": ${err.message}`);
|
|
226
|
+
}
|
|
227
|
+
});
|
|
206
228
|
// Ensure childProcess.pid is defined before proceeding
|
|
207
229
|
if (!childProcess.pid) {
|
|
208
230
|
// Return a consistent error object instead of throwing
|
|
@@ -257,6 +279,23 @@ export class TerminalManager {
|
|
|
257
279
|
}
|
|
258
280
|
resolve(result);
|
|
259
281
|
};
|
|
282
|
+
// Now that resolveOnce exists, route process errors into it: an error after
|
|
283
|
+
// a successful spawn means the process is gone, so the caller must not sit
|
|
284
|
+
// waiting for output that will never arrive.
|
|
285
|
+
forwardProcessError = (err) => {
|
|
286
|
+
this.sessions.delete(childProcess.pid);
|
|
287
|
+
exitReason = 'process_exit';
|
|
288
|
+
resolveOnce({
|
|
289
|
+
pid: childProcess.pid,
|
|
290
|
+
output: output + `\nProcess error: ${err.message}`,
|
|
291
|
+
isBlocked: false
|
|
292
|
+
});
|
|
293
|
+
};
|
|
294
|
+
// An error emitted between spawn and here (the common case — spawn errors
|
|
295
|
+
// land on the next tick) is replayed rather than dropped.
|
|
296
|
+
if (pendingProcessError) {
|
|
297
|
+
forwardProcessError(pendingProcessError);
|
|
298
|
+
}
|
|
260
299
|
childProcess.stdout.on('data', (data) => {
|
|
261
300
|
const text = data.toString();
|
|
262
301
|
const now = Date.now();
|
package/dist/tools/edit.js
CHANGED
|
@@ -239,6 +239,19 @@ RECOMMENDATION: For large search/replace operations, consider breaking them into
|
|
|
239
239
|
// Log to file
|
|
240
240
|
await fuzzySearchLogger.log(logEntry);
|
|
241
241
|
// Combine all fuzzy search data for single capture
|
|
242
|
+
//
|
|
243
|
+
// character_codes (characterCodeData.report) is deliberately NOT sent.
|
|
244
|
+
// It is a frequency map of the characters in the diff between the
|
|
245
|
+
// search text and the file text, so for a short diff it is close to
|
|
246
|
+
// recoverable file content — and mcp-privacy-policy.md states that
|
|
247
|
+
// file contents are not collected. It was added as diagnostics for the
|
|
248
|
+
// CRLF/LF normalization work in #103 (May 2025) to show whether failed
|
|
249
|
+
// matches came from \r (13), \n (10) or non-breaking spaces; that
|
|
250
|
+
// question is long since answered.
|
|
251
|
+
//
|
|
252
|
+
// The scalars below are kept: they are counts and lengths, and carry
|
|
253
|
+
// no recoverable content. The full report still goes to the local
|
|
254
|
+
// fuzzy-search.log for anyone debugging on their own machine.
|
|
242
255
|
const fuzzySearchData = {
|
|
243
256
|
similarity: similarity,
|
|
244
257
|
execution_time_ms: executionTime,
|
|
@@ -246,7 +259,6 @@ RECOMMENDATION: For large search/replace operations, consider breaking them into
|
|
|
246
259
|
file_size: content.length,
|
|
247
260
|
threshold: FUZZY_THRESHOLD,
|
|
248
261
|
found_text_length: fuzzyResult.value.length,
|
|
249
|
-
character_codes: characterCodeData.report,
|
|
250
262
|
unique_character_count: characterCodeData.uniqueCount,
|
|
251
263
|
total_diff_length: characterCodeData.diffLength
|
|
252
264
|
};
|
package/dist/tools/process.d.ts
CHANGED
|
@@ -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>;
|