@wonderwhy-er/desktop-commander 0.3.1-alpha.0 → 0.3.1-alpha.2
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/LICENSE +20 -20
- package/README.md +1152 -1152
- package/dist/bootstrap.js +0 -0
- package/dist/command-manager.js +0 -0
- package/dist/config-field-definitions.js +0 -0
- package/dist/config-manager.d.ts +6 -0
- package/dist/config-manager.js +1 -1
- package/dist/config-recovery.js +0 -0
- package/dist/config.js +0 -0
- package/dist/custom-stdio.js +0 -0
- package/dist/data/onboarding-prompts.json +70 -70
- package/dist/error-handlers.js +0 -0
- package/dist/handlers/filesystem-handlers.js +2 -2
- package/dist/index.js +0 -0
- package/dist/npm-scripts/remote.js +34 -19
- package/dist/remote-device/diagnostics/device-log.d.ts +63 -0
- package/dist/remote-device/diagnostics/device-log.js +219 -0
- package/dist/remote-device/diagnostics/redact.d.ts +1 -0
- package/dist/remote-device/diagnostics/redact.js +76 -0
- package/dist/remote-device/diagnostics/report.d.ts +118 -0
- package/dist/remote-device/diagnostics/report.js +748 -0
- package/dist/remote-device/diagnostics/upload.d.ts +11 -0
- package/dist/remote-device/diagnostics/upload.js +59 -0
- package/dist/remote-device/scripts/blocking-offline-update.js +133 -133
- package/dist/search-manager.js +0 -0
- package/dist/server.js +610 -610
- package/dist/setup-claude-server.js +942 -942
- package/dist/terminal-manager.js +0 -0
- package/dist/tools/edit.js +2 -2
- package/dist/tools/fuzzySearch.js +9 -9
- package/dist/tools/improved-process-tools.js +10 -10
- package/dist/tools/pdf/extract-images.js +1 -1
- package/dist/tools/prompts.js +1 -1
- package/dist/track-installation.js +387 -387
- package/dist/types.js +0 -0
- package/dist/ui/config-editor/index.html +13 -13
- package/dist/ui/config-editor/src/app.js +30 -30
- package/dist/ui/config-editor/src/array-modal.js +32 -32
- package/dist/ui/config-editor/styles.css +586 -586
- package/dist/ui/file-preview/index.html +16 -16
- package/dist/ui/file-preview/src/app.js +8 -8
- package/dist/ui/file-preview/src/document-layout.js +31 -31
- package/dist/ui/file-preview/src/document-outline.js +8 -8
- package/dist/ui/file-preview/src/markdown/conflict-dialog.js +33 -33
- package/dist/ui/file-preview/src/markdown/controller.js +9 -9
- package/dist/ui/file-preview/src/markdown/editor.js +31 -31
- package/dist/ui/file-preview/styles.css +1630 -1630
- package/dist/uninstall-claude-server.js +745 -745
- package/dist/utils/files/binary.js +4 -4
- package/dist/utils/files/excel.js +3 -3
- package/dist/utils/lazy-package.d.ts +5 -3
- package/dist/utils/lazy-package.js +6 -4
- package/dist/utils/system-info.js +90 -90
- package/dist/utils/usageTracker.js +49 -49
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/node_modules/@desktop-commander/telemetry-contract/README.md +56 -56
- package/node_modules/@desktop-commander/telemetry-contract/package.json +32 -32
- package/node_modules/@desktop-commander/telemetry-contract/transport.d.ts +38 -38
- package/node_modules/@desktop-commander/telemetry-contract/transport.js +164 -164
- package/package.json +29 -15
- package/vendor/telemetry-contract/README.md +56 -56
- package/vendor/telemetry-contract/package.json +32 -32
- package/vendor/telemetry-contract/transport.d.ts +38 -38
- package/vendor/telemetry-contract/transport.js +164 -164
- package/vendor/telemetry-contract/transport.test.js +39 -39
- package/dist/remote-device/broadcast-analytics.d.ts +0 -28
- package/dist/remote-device/broadcast-analytics.js +0 -41
- package/dist/remote-device/mqtt-enrollment.d.ts +0 -16
- package/dist/remote-device/mqtt-enrollment.js +0 -162
- package/dist/remote-device/mqtt-transport.d.ts +0 -44
- package/dist/remote-device/mqtt-transport.js +0 -197
- package/dist/remote-device/transport-analytics.d.ts +0 -29
- package/dist/remote-device/transport-analytics.js +0 -44
- package/dist/tools/search.d.ts +0 -32
- package/dist/tools/search.js +0 -202
|
@@ -0,0 +1,748 @@
|
|
|
1
|
+
import { exec, execFile } from 'child_process';
|
|
2
|
+
import dns from 'dns';
|
|
3
|
+
import fs from 'fs';
|
|
4
|
+
import net from 'net';
|
|
5
|
+
import { createRequire } from 'module';
|
|
6
|
+
import os from 'os';
|
|
7
|
+
import path from 'path';
|
|
8
|
+
import tls from 'tls';
|
|
9
|
+
import { fileURLToPath } from 'url';
|
|
10
|
+
import PizZip from 'pizzip';
|
|
11
|
+
import { parseConfig } from '../../config-manager.js';
|
|
12
|
+
import { VERSION } from '../../version.js';
|
|
13
|
+
import { deviceLogNames, getDeviceLogDir, cleanLine } from './device-log.js';
|
|
14
|
+
import { redact } from './redact.js';
|
|
15
|
+
import { savedUserId, uploadReport } from './upload.js';
|
|
16
|
+
/**
|
|
17
|
+
* `desktop-commander remote --report`: a diagnostics zip a user sends to
|
|
18
|
+
* support. It doesn't start the device and never opens sign-in, so it works
|
|
19
|
+
* when sign-in is broken. After saving, it uploads the zip (upload.ts) unless
|
|
20
|
+
* --no-upload, and prints the report id to give support.
|
|
21
|
+
*
|
|
22
|
+
* Only listed facts go in: versions (npm included), how Node runs (the Node
|
|
23
|
+
* executable and the entry script, home folder as ~), the clock skew from the
|
|
24
|
+
* server's Date header, network timings (server, Supabase REST, realtime
|
|
25
|
+
* websocket), the device id and yes/no facts about the rest of device.json,
|
|
26
|
+
* telemetryEnabled and clientId from config.json, and the device log
|
|
27
|
+
* re-filtered and re-masked. Paths and error texts pass through redact().
|
|
28
|
+
* Tokens, emails, the user name and tool arguments or results never go in.
|
|
29
|
+
*/
|
|
30
|
+
const DEFAULT_SERVER_URL = 'https://mcp.desktopcommander.app';
|
|
31
|
+
const CONNECT_TIMEOUT_MS = 4000;
|
|
32
|
+
const REQUEST_TIMEOUT_MS = 5000;
|
|
33
|
+
const MCP_INFO_ROUNDS = 5;
|
|
34
|
+
const NPM_TIMEOUT_MS = 5000;
|
|
35
|
+
const PROCESS_LIST_TIMEOUT_MS = 10000;
|
|
36
|
+
/** The npm package, and the MCPB bundle (named from manifest.json). */
|
|
37
|
+
const PACKAGE_NAMES = new Set(['@wonderwhy-er/desktop-commander', 'desktop-commander']);
|
|
38
|
+
/** `desktop-commander <these>` is not the MCP server. */
|
|
39
|
+
const NOT_THE_SERVER = new Set(['remote', 'setup', 'remove']);
|
|
40
|
+
/** A rotated log file is 1 MB at most; read no more than this of a larger one. */
|
|
41
|
+
const MAX_LOG_READ_BYTES = 2 * 1024 * 1024;
|
|
42
|
+
// --- small helpers ---------------------------------------------------------------
|
|
43
|
+
/** Short reasons for the network errors a user's machine typically gives. */
|
|
44
|
+
const NETWORK_REASONS = {
|
|
45
|
+
ECONNREFUSED: 'connection refused',
|
|
46
|
+
ECONNRESET: 'connection reset',
|
|
47
|
+
ETIMEDOUT: 'timed out',
|
|
48
|
+
UND_ERR_CONNECT_TIMEOUT: 'timed out',
|
|
49
|
+
ENOTFOUND: 'name not found',
|
|
50
|
+
EAI_AGAIN: 'name lookup failed',
|
|
51
|
+
EHOSTUNREACH: 'host unreachable',
|
|
52
|
+
ENETUNREACH: 'network unreachable',
|
|
53
|
+
};
|
|
54
|
+
function errorText(error) {
|
|
55
|
+
const err = error;
|
|
56
|
+
if (err?.name === 'TimeoutError' || err?.name === 'AbortError')
|
|
57
|
+
return 'timed out';
|
|
58
|
+
// fetch() wraps the socket error in `cause`
|
|
59
|
+
const code = String(err?.code ?? err?.cause?.code ?? '');
|
|
60
|
+
if (NETWORK_REASONS[code])
|
|
61
|
+
return NETWORK_REASONS[code];
|
|
62
|
+
if (/CERT|SELF_SIGNED/.test(code))
|
|
63
|
+
return `certificate problem (${code})`;
|
|
64
|
+
const cause = err?.cause?.message;
|
|
65
|
+
const message = String(err?.message ?? error);
|
|
66
|
+
const firstLine = (cause && !message.includes(cause) ? `${message} (${cause})` : message).split(/\r?\n/)[0];
|
|
67
|
+
return redact(firstLine).slice(0, 200);
|
|
68
|
+
}
|
|
69
|
+
function elapsed(startedAt) {
|
|
70
|
+
return Math.round(Number(process.hrtime.bigint() - startedAt) / 1e6);
|
|
71
|
+
}
|
|
72
|
+
function withTimeout(promise, ms) {
|
|
73
|
+
let timer;
|
|
74
|
+
return Promise.race([
|
|
75
|
+
promise,
|
|
76
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('timed out')), ms); }),
|
|
77
|
+
]).finally(() => clearTimeout(timer));
|
|
78
|
+
}
|
|
79
|
+
function median(values) {
|
|
80
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
81
|
+
return sorted[Math.floor(sorted.length / 2)];
|
|
82
|
+
}
|
|
83
|
+
function yesNo(value) {
|
|
84
|
+
return value ? 'yes' : 'no';
|
|
85
|
+
}
|
|
86
|
+
// --- versions -------------------------------------------------------------------------
|
|
87
|
+
function runKind() {
|
|
88
|
+
if (process.env.MCP_DXT)
|
|
89
|
+
return 'MCPB';
|
|
90
|
+
const here = fileURLToPath(import.meta.url);
|
|
91
|
+
const parts = here.split(/[\\/]/);
|
|
92
|
+
if (parts.includes('_npx'))
|
|
93
|
+
return 'npx';
|
|
94
|
+
// dist/remote-device/diagnostics/report.js -> the package root
|
|
95
|
+
const root = path.resolve(path.dirname(here), '..', '..', '..');
|
|
96
|
+
if (fs.existsSync(path.join(root, '.git')) || fs.existsSync(path.join(root, 'src', 'version.ts')))
|
|
97
|
+
return 'dev checkout';
|
|
98
|
+
if (parts.includes('node_modules'))
|
|
99
|
+
return 'global npm';
|
|
100
|
+
return 'unknown';
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Which installer the Node executable comes from, read from its path. A path
|
|
104
|
+
* none of these match is "unknown": the report shows the path itself anyway.
|
|
105
|
+
*/
|
|
106
|
+
export function nodeKind(execPath) {
|
|
107
|
+
const p = execPath.replace(/\\/g, '/').toLowerCase();
|
|
108
|
+
if (/\/(\.nvm|nvm|nvm4w)\//.test(p))
|
|
109
|
+
return 'nvm';
|
|
110
|
+
if (/\/(\.fnm|fnm|fnm_multishells)\//.test(p))
|
|
111
|
+
return 'fnm';
|
|
112
|
+
if (/\/(\.volta|volta)\//.test(p))
|
|
113
|
+
return 'Volta';
|
|
114
|
+
if (p.includes('/.asdf/'))
|
|
115
|
+
return 'asdf';
|
|
116
|
+
if (/\/mise\/installs\//.test(p))
|
|
117
|
+
return 'mise';
|
|
118
|
+
if (/\/(claude\.app|anthropicclaude)\//.test(p))
|
|
119
|
+
return "Claude Desktop's bundled Node";
|
|
120
|
+
if (/^\/(opt\/homebrew|usr\/local\/cellar|home\/linuxbrew)\//.test(p))
|
|
121
|
+
return 'Homebrew';
|
|
122
|
+
if (p.includes('/program files/nodejs/') || /^\/usr\/(local\/)?bin\//.test(p))
|
|
123
|
+
return 'global install';
|
|
124
|
+
return 'unknown';
|
|
125
|
+
}
|
|
126
|
+
function npmVersion() {
|
|
127
|
+
return new Promise((resolve) => {
|
|
128
|
+
// A fixed command line through the shell: npm is npm.cmd on Windows, which needs one
|
|
129
|
+
exec('npm --version', {
|
|
130
|
+
timeout: NPM_TIMEOUT_MS,
|
|
131
|
+
windowsHide: true,
|
|
132
|
+
// --version needs no registry: keep npm's update check off the network
|
|
133
|
+
env: { ...process.env, npm_config_update_notifier: 'false' },
|
|
134
|
+
}, (error, stdout) => {
|
|
135
|
+
const version = String(stdout).trim();
|
|
136
|
+
resolve(!error && /^\d+\.\d+\.\d+\S*$/.test(version) ? version : null);
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
function macosVersion() {
|
|
141
|
+
return new Promise((resolve) => {
|
|
142
|
+
execFile('sw_vers', ['-productVersion'], { timeout: 2000 }, (error, stdout) => {
|
|
143
|
+
resolve(error ? null : String(stdout).trim() || null);
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
async function osName() {
|
|
148
|
+
if (process.platform === 'win32')
|
|
149
|
+
return os.version() || 'Windows';
|
|
150
|
+
if (process.platform === 'darwin') {
|
|
151
|
+
const version = await macosVersion();
|
|
152
|
+
return version ? `macOS ${version}` : 'macOS';
|
|
153
|
+
}
|
|
154
|
+
if (process.platform === 'linux') {
|
|
155
|
+
try {
|
|
156
|
+
const release = fs.readFileSync('/etc/os-release', 'utf8');
|
|
157
|
+
const pretty = release.match(/^PRETTY_NAME="?([^"\n]*)"?$/m)?.[1];
|
|
158
|
+
if (pretty)
|
|
159
|
+
return pretty;
|
|
160
|
+
}
|
|
161
|
+
catch { /* fall through */ }
|
|
162
|
+
return 'Linux';
|
|
163
|
+
}
|
|
164
|
+
return os.type();
|
|
165
|
+
}
|
|
166
|
+
// --- network ----------------------------------------------------------------------------
|
|
167
|
+
/** DNS, then the TLS handshake (https) or TCP connect (http). `name` is how the report shows the host. */
|
|
168
|
+
async function timeHost(url, name) {
|
|
169
|
+
const host = url.hostname;
|
|
170
|
+
const result = { host: name };
|
|
171
|
+
try {
|
|
172
|
+
const startedAt = process.hrtime.bigint();
|
|
173
|
+
await withTimeout(dns.promises.lookup(host), CONNECT_TIMEOUT_MS);
|
|
174
|
+
result.dnsMs = elapsed(startedAt);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
result.error = `DNS failed (${errorText(error)})`;
|
|
178
|
+
return result;
|
|
179
|
+
}
|
|
180
|
+
const secure = url.protocol === 'https:' || url.protocol === 'wss:';
|
|
181
|
+
const port = Number(url.port) || (secure ? 443 : 80);
|
|
182
|
+
try {
|
|
183
|
+
const startedAt = process.hrtime.bigint();
|
|
184
|
+
await new Promise((resolve, reject) => {
|
|
185
|
+
const socket = secure
|
|
186
|
+
? tls.connect({ host, port, servername: net.isIP(host) ? undefined : host }, () => { socket.destroy(); resolve(); })
|
|
187
|
+
: net.connect({ host, port }, () => { socket.destroy(); resolve(); });
|
|
188
|
+
socket.setTimeout(CONNECT_TIMEOUT_MS, () => { socket.destroy(); reject(new Error('timed out')); });
|
|
189
|
+
socket.on('error', reject);
|
|
190
|
+
});
|
|
191
|
+
result.connect = { kind: secure ? 'TLS' : 'TCP', ms: elapsed(startedAt) };
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
result.error = `${secure ? 'TLS' : 'TCP'} failed (${errorText(error)})`;
|
|
195
|
+
}
|
|
196
|
+
return result;
|
|
197
|
+
}
|
|
198
|
+
async function checkMcpInfo(serverUrl) {
|
|
199
|
+
const ms = [];
|
|
200
|
+
const statuses = [];
|
|
201
|
+
const offsets = [];
|
|
202
|
+
let info = null;
|
|
203
|
+
let error;
|
|
204
|
+
for (let round = 0; round < MCP_INFO_ROUNDS; round++) {
|
|
205
|
+
const sentAt = Date.now();
|
|
206
|
+
const startedAt = process.hrtime.bigint();
|
|
207
|
+
try {
|
|
208
|
+
const response = await fetch(`${serverUrl}/api/mcp-info`, { signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
|
|
209
|
+
const body = await response.text();
|
|
210
|
+
ms.push(elapsed(startedAt));
|
|
211
|
+
statuses.push(response.status);
|
|
212
|
+
const serverMs = Date.parse(response.headers.get('date') ?? '');
|
|
213
|
+
if (!Number.isNaN(serverMs))
|
|
214
|
+
offsets.push(serverMs - (sentAt + Date.now()) / 2);
|
|
215
|
+
if (response.ok && !info) {
|
|
216
|
+
try {
|
|
217
|
+
info = JSON.parse(body);
|
|
218
|
+
}
|
|
219
|
+
catch {
|
|
220
|
+
error = 'mcp-info is not JSON';
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch (err) {
|
|
225
|
+
error = errorText(err);
|
|
226
|
+
// Stop at the first failure: four more timeouts would only make the user wait
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return { ms, statuses, offsets, info, error };
|
|
231
|
+
}
|
|
232
|
+
async function checkRest(supabaseUrl, key) {
|
|
233
|
+
const startedAt = process.hrtime.bigint();
|
|
234
|
+
try {
|
|
235
|
+
const response = await fetch(`${supabaseUrl}/rest/v1/`, {
|
|
236
|
+
headers: { apikey: key },
|
|
237
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
238
|
+
});
|
|
239
|
+
await response.arrayBuffer();
|
|
240
|
+
return { status: response.status, ms: elapsed(startedAt) };
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
return { error: errorText(error) };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/** Node 22+ has WebSocket built in; older Node uses `ws`, which realtime-js depends on. */
|
|
247
|
+
function webSocketClass() {
|
|
248
|
+
if (typeof globalThis.WebSocket === 'function')
|
|
249
|
+
return globalThis.WebSocket;
|
|
250
|
+
try {
|
|
251
|
+
return createRequire(import.meta.url)('ws');
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
return null;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
function checkRealtime(supabaseUrl, key) {
|
|
258
|
+
const WebSocketClass = webSocketClass();
|
|
259
|
+
if (!WebSocketClass)
|
|
260
|
+
return Promise.resolve({ heartbeat: false, error: 'no WebSocket in this Node version' });
|
|
261
|
+
const url = `${supabaseUrl.replace(/^http/, 'ws')}/realtime/v1/websocket?apikey=${encodeURIComponent(key)}&vsn=1.0.0`;
|
|
262
|
+
return new Promise((resolve) => {
|
|
263
|
+
const result = { heartbeat: false };
|
|
264
|
+
const startedAt = process.hrtime.bigint();
|
|
265
|
+
let heartbeatAt;
|
|
266
|
+
let socket;
|
|
267
|
+
let done = false;
|
|
268
|
+
const finish = (error) => {
|
|
269
|
+
// The close that follows a finished check is not a failure
|
|
270
|
+
if (done)
|
|
271
|
+
return;
|
|
272
|
+
done = true;
|
|
273
|
+
clearTimeout(timer);
|
|
274
|
+
if (error)
|
|
275
|
+
result.error = error;
|
|
276
|
+
try {
|
|
277
|
+
socket?.close();
|
|
278
|
+
}
|
|
279
|
+
catch { /* already closed */ }
|
|
280
|
+
resolve(result);
|
|
281
|
+
};
|
|
282
|
+
const timer = setTimeout(() => finish(result.openedMs === undefined ? 'opening timed out' : 'heartbeat not answered in time'), REQUEST_TIMEOUT_MS);
|
|
283
|
+
try {
|
|
284
|
+
socket = new WebSocketClass(url);
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
finish(errorText(error));
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
socket.onopen = () => {
|
|
291
|
+
result.openedMs = elapsed(startedAt);
|
|
292
|
+
heartbeatAt = process.hrtime.bigint();
|
|
293
|
+
socket.send(JSON.stringify({ topic: 'phoenix', event: 'heartbeat', payload: {}, ref: '1' }));
|
|
294
|
+
};
|
|
295
|
+
socket.onmessage = (event) => {
|
|
296
|
+
try {
|
|
297
|
+
const message = JSON.parse(String(event.data));
|
|
298
|
+
if (message.ref === '1' && message.event === 'phx_reply') {
|
|
299
|
+
result.heartbeat = message.payload?.status === 'ok';
|
|
300
|
+
result.heartbeatMs = elapsed(heartbeatAt);
|
|
301
|
+
finish(result.heartbeat ? undefined : 'heartbeat refused');
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
catch { /* not ours */ }
|
|
305
|
+
};
|
|
306
|
+
socket.onerror = (event) => finish(event?.message ? errorText(event) : 'connection failed');
|
|
307
|
+
socket.onclose = (event) => finish(`closed (${event?.code ?? '?'})`);
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
/** "[[dd-]hh:]mm:ss" from ps, in seconds. */
|
|
311
|
+
function elapsedSeconds(etime) {
|
|
312
|
+
const [days, clock] = etime.includes('-') ? etime.split('-') : ['0', etime];
|
|
313
|
+
const parts = clock.split(':').map(Number);
|
|
314
|
+
while (parts.length < 3)
|
|
315
|
+
parts.unshift(0);
|
|
316
|
+
return Number(days) * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2];
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Every process with its command line and start time. process.ts's list uses
|
|
320
|
+
* tasklist on Windows, which has no command lines, hence Win32_Process here.
|
|
321
|
+
*/
|
|
322
|
+
function listProcesses() {
|
|
323
|
+
const options = { timeout: PROCESS_LIST_TIMEOUT_MS, windowsHide: true, maxBuffer: 32 * 1024 * 1024 };
|
|
324
|
+
return new Promise((resolve, reject) => {
|
|
325
|
+
if (process.platform === 'win32') {
|
|
326
|
+
const script = '[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-CimInstance Win32_Process | ForEach-Object { ' +
|
|
327
|
+
'"$($_.ProcessId)`t$(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString(\'o\') })`t$($_.CommandLine)" }';
|
|
328
|
+
execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], options, (error, stdout) => {
|
|
329
|
+
if (error)
|
|
330
|
+
return reject(error);
|
|
331
|
+
resolve(String(stdout).split(/\r?\n/).map((line) => {
|
|
332
|
+
const [pid, created, ...command] = line.split('\t');
|
|
333
|
+
return { pid: Number(pid), startedAt: Date.parse(created), command: command.join('\t') };
|
|
334
|
+
}).filter((p) => p.pid > 0 && p.command));
|
|
335
|
+
});
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
execFile('ps', ['-A', '-ww', '-o', 'pid=,etime=,command='], options, (error, stdout) => {
|
|
339
|
+
if (error)
|
|
340
|
+
return reject(error);
|
|
341
|
+
const now = Date.now();
|
|
342
|
+
resolve(String(stdout).split('\n').flatMap((line) => {
|
|
343
|
+
const match = line.match(/^\s*(\d+)\s+(\S+)\s+(.*)$/);
|
|
344
|
+
return match ? [{ pid: Number(match[1]), startedAt: now - elapsedSeconds(match[2]) * 1000, command: match[3] }] : [];
|
|
345
|
+
}));
|
|
346
|
+
});
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
/** Whether `file` is Desktop Commander's dist/index.js: a bin link is followed, then the package.json beside dist/ named. */
|
|
350
|
+
function isDesktopCommanderEntry(file, packageNames) {
|
|
351
|
+
let entry;
|
|
352
|
+
try {
|
|
353
|
+
entry = fs.realpathSync(file);
|
|
354
|
+
}
|
|
355
|
+
catch {
|
|
356
|
+
return false;
|
|
357
|
+
}
|
|
358
|
+
if (path.basename(entry) !== 'index.js' || path.basename(path.dirname(entry)) !== 'dist')
|
|
359
|
+
return false;
|
|
360
|
+
const root = path.dirname(path.dirname(entry));
|
|
361
|
+
if (!packageNames.has(root)) {
|
|
362
|
+
try {
|
|
363
|
+
packageNames.set(root, JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')).name ?? null);
|
|
364
|
+
}
|
|
365
|
+
catch {
|
|
366
|
+
packageNames.set(root, null);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return PACKAGE_NAMES.has(packageNames.get(root) ?? '');
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* Processes running Desktop Commander's MCP server: a command line with its
|
|
373
|
+
* dist/index.js (started by an MCP client, npx, or `remote`'s local MCP), not
|
|
374
|
+
* followed by `remote` / `setup` / `remove`, and not this report. A shell
|
|
375
|
+
* wrapping it names only a bin, which doesn't resolve, so it isn't counted
|
|
376
|
+
* twice. Only the count and the earliest start leave this function.
|
|
377
|
+
*/
|
|
378
|
+
async function desktopCommanderMcp() {
|
|
379
|
+
let processes;
|
|
380
|
+
try {
|
|
381
|
+
processes = await listProcesses();
|
|
382
|
+
}
|
|
383
|
+
catch (error) {
|
|
384
|
+
return { running: null, since: null, error: `could not list processes (${errorText(error)})` };
|
|
385
|
+
}
|
|
386
|
+
const packageNames = new Map();
|
|
387
|
+
const servers = processes.filter(({ pid, command }) => {
|
|
388
|
+
if (pid === process.pid)
|
|
389
|
+
return false;
|
|
390
|
+
const tokens = (command.match(/"[^"]*"|\S+/g) ?? []).map((token) => token.replace(/^"|"$/g, ''));
|
|
391
|
+
// The first token is the executable; the entry is any later one
|
|
392
|
+
const at = tokens.findIndex((token, i) => i > 0 && /(\.js|desktop-commander(\.cmd)?)$/i.test(token) &&
|
|
393
|
+
isDesktopCommanderEntry(token, packageNames));
|
|
394
|
+
return at > 0 && !NOT_THE_SERVER.has(tokens[at + 1] ?? '');
|
|
395
|
+
});
|
|
396
|
+
const starts = servers.map((p) => p.startedAt).filter((t) => !Number.isNaN(t));
|
|
397
|
+
return {
|
|
398
|
+
running: servers.length,
|
|
399
|
+
since: starts.length ? new Date(Math.min(...starts)).toISOString() : null,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
function proxySet(...names) {
|
|
403
|
+
return names.some((name) => Boolean(process.env[name]));
|
|
404
|
+
}
|
|
405
|
+
// --- device state, settings, device log --------------------------------------------------
|
|
406
|
+
function deviceState(home) {
|
|
407
|
+
const file = path.join(home, '.desktop-commander-device', 'device.json');
|
|
408
|
+
const state = {
|
|
409
|
+
deviceJson: false, parses: false, id: null, session: false,
|
|
410
|
+
accessToken: false, refreshToken: false, savedAt: null,
|
|
411
|
+
};
|
|
412
|
+
let text;
|
|
413
|
+
try {
|
|
414
|
+
state.savedAt = new Date(fs.statSync(file).mtimeMs).toISOString();
|
|
415
|
+
text = fs.readFileSync(file, 'utf8');
|
|
416
|
+
state.deviceJson = true;
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
return state;
|
|
420
|
+
}
|
|
421
|
+
try {
|
|
422
|
+
const config = JSON.parse(text);
|
|
423
|
+
state.parses = true;
|
|
424
|
+
// Only an id-shaped value: whatever else a hand-edited file holds stays out
|
|
425
|
+
const id = config?.deviceId;
|
|
426
|
+
state.id = typeof id === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(id) ? id : null;
|
|
427
|
+
const session = config?.session;
|
|
428
|
+
state.session = Boolean(session) && typeof session === 'object';
|
|
429
|
+
state.accessToken = typeof session?.access_token === 'string' && session.access_token.length > 0;
|
|
430
|
+
state.refreshToken = typeof session?.refresh_token === 'string' && session.refresh_token.length > 0;
|
|
431
|
+
}
|
|
432
|
+
catch { /* parses stays false */ }
|
|
433
|
+
return state;
|
|
434
|
+
}
|
|
435
|
+
function settings(home) {
|
|
436
|
+
try {
|
|
437
|
+
// As Desktop Commander reads it: a file saved with a UTF-8 BOM too
|
|
438
|
+
const config = parseConfig(fs.readFileSync(path.join(home, '.claude-server-commander', 'config.json'), 'utf8'));
|
|
439
|
+
const clientId = typeof config?.clientId === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(config.clientId) ? config.clientId : null;
|
|
440
|
+
return {
|
|
441
|
+
telemetryEnabled: typeof config?.telemetryEnabled === 'boolean' ? config.telemetryEnabled : null,
|
|
442
|
+
clientId,
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
catch {
|
|
446
|
+
return { telemetryEnabled: null, clientId: null };
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
function readTail(file) {
|
|
450
|
+
const size = fs.statSync(file).size;
|
|
451
|
+
if (size <= MAX_LOG_READ_BYTES)
|
|
452
|
+
return fs.readFileSync(file, 'utf8');
|
|
453
|
+
const fd = fs.openSync(file, 'r');
|
|
454
|
+
try {
|
|
455
|
+
const buffer = Buffer.alloc(MAX_LOG_READ_BYTES);
|
|
456
|
+
fs.readSync(fd, buffer, 0, MAX_LOG_READ_BYTES, size - MAX_LOG_READ_BYTES);
|
|
457
|
+
return buffer.toString('utf8');
|
|
458
|
+
}
|
|
459
|
+
finally {
|
|
460
|
+
fs.closeSync(fd);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
const LOG_LINE = /^(\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ) {2}(.*)$/;
|
|
464
|
+
/** A rotated file's number: remote-mon.2.log is 2, remote-mon.log 0. */
|
|
465
|
+
const rotation = (name) => Number(name.match(/\.(\d+)\.log$/)?.[1] ?? 0);
|
|
466
|
+
/**
|
|
467
|
+
* The device log files (the 21 fixed names that exist), oldest first by
|
|
468
|
+
* modification time, each timestamped line cleaned and masked again.
|
|
469
|
+
*/
|
|
470
|
+
function deviceLog(dir) {
|
|
471
|
+
const parts = [];
|
|
472
|
+
const summary = { files: 0, lines: 0, first: null, last: null, lastText: null };
|
|
473
|
+
const files = deviceLogNames().flatMap((name) => {
|
|
474
|
+
try {
|
|
475
|
+
return [{ name, mtime: fs.statSync(path.join(dir, name)).mtimeMs }];
|
|
476
|
+
}
|
|
477
|
+
catch {
|
|
478
|
+
return [];
|
|
479
|
+
}
|
|
480
|
+
}).sort((a, b) => a.mtime - b.mtime || rotation(b.name) - rotation(a.name));
|
|
481
|
+
for (const { name } of files) {
|
|
482
|
+
let raw;
|
|
483
|
+
try {
|
|
484
|
+
raw = readTail(path.join(dir, name));
|
|
485
|
+
}
|
|
486
|
+
catch {
|
|
487
|
+
continue;
|
|
488
|
+
}
|
|
489
|
+
const kept = [];
|
|
490
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
491
|
+
const match = line.match(LOG_LINE);
|
|
492
|
+
const text = match && cleanLine(match[2]);
|
|
493
|
+
if (!match || !text)
|
|
494
|
+
continue;
|
|
495
|
+
kept.push(`${match[1]} ${text}`);
|
|
496
|
+
summary.first ?? (summary.first = match[1]);
|
|
497
|
+
summary.last = match[1];
|
|
498
|
+
summary.lastText = text;
|
|
499
|
+
}
|
|
500
|
+
summary.files++;
|
|
501
|
+
summary.lines += kept.length;
|
|
502
|
+
parts.push({ name, text: kept.length ? kept.join('\n') + '\n' : '' });
|
|
503
|
+
}
|
|
504
|
+
return { parts, summary };
|
|
505
|
+
}
|
|
506
|
+
// --- the report ---------------------------------------------------------------------------
|
|
507
|
+
/** Hosts on this machine: an http address there never crosses the network (a local stand-in). */
|
|
508
|
+
const LOOPBACK_HOSTS = ['127.0.0.1', 'localhost', '[::1]'];
|
|
509
|
+
/** The diagnostics Worker's address from /api/mcp-info: https, or http on this machine only. */
|
|
510
|
+
function uploadUrl(value) {
|
|
511
|
+
if (typeof value !== 'string')
|
|
512
|
+
return null;
|
|
513
|
+
try {
|
|
514
|
+
const url = new URL(value);
|
|
515
|
+
return url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.includes(url.hostname)) ? value : null;
|
|
516
|
+
}
|
|
517
|
+
catch {
|
|
518
|
+
return null;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
export async function collectReport() {
|
|
522
|
+
const home = os.homedir();
|
|
523
|
+
const now = Date.now();
|
|
524
|
+
const serverUrl = (process.env.MCP_SERVER_URL || DEFAULT_SERVER_URL).replace(/\/+$/, '');
|
|
525
|
+
const server = new URL(serverUrl);
|
|
526
|
+
const [name, npm, mcp, serverTiming] = await Promise.all([
|
|
527
|
+
osName(), npmVersion(), desktopCommanderMcp(), timeHost(server, server.host),
|
|
528
|
+
]);
|
|
529
|
+
const mcpInfo = await checkMcpInfo(serverUrl);
|
|
530
|
+
let supabase;
|
|
531
|
+
const supabaseUrl = mcpInfo.info?.supabaseUrl?.replace(/\/+$/, '');
|
|
532
|
+
const key = mcpInfo.info?.supabasePublishableKey;
|
|
533
|
+
if (supabaseUrl && key) {
|
|
534
|
+
// Shown as "Supabase": the project's address isn't needed to read the report
|
|
535
|
+
const timing = await timeHost(new URL(supabaseUrl), 'Supabase');
|
|
536
|
+
const rest = await checkRest(supabaseUrl, key);
|
|
537
|
+
const realtime = await checkRealtime(supabaseUrl, key);
|
|
538
|
+
supabase = { ...timing, rest, realtime };
|
|
539
|
+
}
|
|
540
|
+
else {
|
|
541
|
+
supabase = { error: mcpInfo.error ? 'skipped: no answer from /api/mcp-info' : 'skipped: /api/mcp-info gave no Supabase address' };
|
|
542
|
+
}
|
|
543
|
+
const log = deviceLog(getDeviceLogDir());
|
|
544
|
+
const report = {
|
|
545
|
+
format: 1,
|
|
546
|
+
createdAt: new Date(now).toISOString(),
|
|
547
|
+
versions: {
|
|
548
|
+
desktopCommander: VERSION,
|
|
549
|
+
node: process.versions.node,
|
|
550
|
+
npm,
|
|
551
|
+
os: { name, release: os.release(), arch: os.arch() },
|
|
552
|
+
// Paths with the home folder as ~: the user name never appears, the rest of the path does
|
|
553
|
+
nodePath: redact(process.execPath),
|
|
554
|
+
nodeKind: nodeKind(process.execPath),
|
|
555
|
+
entryPath: process.argv[1] ? redact(process.argv[1]) : 'unknown',
|
|
556
|
+
runKind: runKind(),
|
|
557
|
+
},
|
|
558
|
+
clock: mcpInfo.offsets.length
|
|
559
|
+
? { serverAheadSeconds: Math.round(median(mcpInfo.offsets) / 1000) }
|
|
560
|
+
: { serverAheadSeconds: null, error: 'no Date header from the server' },
|
|
561
|
+
network: {
|
|
562
|
+
server: { ...serverTiming, mcpInfo: { ms: mcpInfo.ms, statuses: mcpInfo.statuses, error: mcpInfo.error } },
|
|
563
|
+
supabase,
|
|
564
|
+
proxy: { httpsProxy: proxySet('HTTPS_PROXY', 'https_proxy'), httpProxy: proxySet('HTTP_PROXY', 'http_proxy') },
|
|
565
|
+
},
|
|
566
|
+
device: deviceState(home),
|
|
567
|
+
settings: settings(home),
|
|
568
|
+
deviceLog: log.summary,
|
|
569
|
+
desktopCommanderMcp: mcp,
|
|
570
|
+
};
|
|
571
|
+
return { report, logParts: log.parts, diagnosticsUrl: uploadUrl(mcpInfo.info?.diagnosticsUrl) };
|
|
572
|
+
}
|
|
573
|
+
function networkOk(network) {
|
|
574
|
+
const { server, supabase } = network;
|
|
575
|
+
if (server.error || server.mcpInfo.error || server.mcpInfo.ms.length < MCP_INFO_ROUNDS)
|
|
576
|
+
return false;
|
|
577
|
+
if (server.mcpInfo.statuses.some((status) => status !== 200))
|
|
578
|
+
return false;
|
|
579
|
+
if ('rest' in supabase) {
|
|
580
|
+
const { rest, realtime } = supabase;
|
|
581
|
+
return !supabase.error && !rest.error && (rest.status ?? 0) < 500 && realtime.heartbeat;
|
|
582
|
+
}
|
|
583
|
+
return false;
|
|
584
|
+
}
|
|
585
|
+
function hostLine(timing) {
|
|
586
|
+
const parts = [];
|
|
587
|
+
if (timing.dnsMs !== undefined)
|
|
588
|
+
parts.push(`DNS ${timing.dnsMs} ms`);
|
|
589
|
+
if (timing.connect)
|
|
590
|
+
parts.push(`${timing.connect.kind} ${timing.connect.ms} ms`);
|
|
591
|
+
if (timing.error)
|
|
592
|
+
parts.push(timing.error);
|
|
593
|
+
return parts.join(' · ');
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* The REST probe has no sign-in, so any HTTP answer (401 included) means
|
|
597
|
+
* Supabase is reachable; only a 5xx is the server's own failure. report.json
|
|
598
|
+
* keeps the raw status.
|
|
599
|
+
*/
|
|
600
|
+
function restText(rest) {
|
|
601
|
+
if (rest.error || rest.status === undefined)
|
|
602
|
+
return `not reachable (${rest.error ?? 'no answer'})`;
|
|
603
|
+
if (rest.status >= 500)
|
|
604
|
+
return `answered with a server error (${rest.status}) in ${rest.ms} ms`;
|
|
605
|
+
return `reachable in ${rest.ms} ms`;
|
|
606
|
+
}
|
|
607
|
+
function localTimestamp(date) {
|
|
608
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
609
|
+
const offset = -date.getTimezoneOffset();
|
|
610
|
+
const hours = Math.trunc(Math.abs(offset) / 60);
|
|
611
|
+
const minutes = Math.abs(offset) % 60;
|
|
612
|
+
const zone = `UTC${offset < 0 ? '-' : '+'}${hours}${minutes ? `:${pad(minutes)}` : ''}`;
|
|
613
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ` +
|
|
614
|
+
`${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())} (${zone})`;
|
|
615
|
+
}
|
|
616
|
+
/** An ISO time (UTC) to the minute: "2026-10-05 14:21". */
|
|
617
|
+
const utcMinute = (iso) => iso.slice(0, 16).replace('T', ' ');
|
|
618
|
+
/** "running (2 copies, since 14:02)": the time alone if it's today, else with the date. */
|
|
619
|
+
function mcpText(mcp) {
|
|
620
|
+
if (mcp.running === null)
|
|
621
|
+
return `unknown (${mcp.error})`;
|
|
622
|
+
if (mcp.running === 0)
|
|
623
|
+
return 'not running';
|
|
624
|
+
const copies = mcp.running === 1 ? '1 copy' : `${mcp.running} copies`;
|
|
625
|
+
if (!mcp.since)
|
|
626
|
+
return `running (${copies})`;
|
|
627
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
628
|
+
const since = new Date(mcp.since);
|
|
629
|
+
const day = `${since.getFullYear()}-${pad(since.getMonth() + 1)}-${pad(since.getDate())}`;
|
|
630
|
+
const time = `${pad(since.getHours())}:${pad(since.getMinutes())}`;
|
|
631
|
+
const today = new Date();
|
|
632
|
+
const isToday = day === `${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}`;
|
|
633
|
+
return `running (${copies}, since ${isToday ? time : `${day} ${time}`})`;
|
|
634
|
+
}
|
|
635
|
+
export function formatReport(report) {
|
|
636
|
+
const label = (name) => name.padEnd(14);
|
|
637
|
+
const indent = ' '.repeat(14);
|
|
638
|
+
const lines = [];
|
|
639
|
+
const { versions, clock, network, device, settings: config, deviceLog: log } = report;
|
|
640
|
+
lines.push(`Desktop Commander diagnostics — ${localTimestamp(new Date(report.createdAt))}`);
|
|
641
|
+
lines.push('This file contains: versions, how Node runs (paths, with the home folder as ~), clock, network checks, ' +
|
|
642
|
+
'the device id and whether sign-in data exists (yes/no), device status history.');
|
|
643
|
+
lines.push('It does not contain: tokens, passwords, emails, the user name, tool arguments or results.');
|
|
644
|
+
lines.push('');
|
|
645
|
+
lines.push(`${label('Versions')}Desktop Commander ${versions.desktopCommander} · Node ${versions.node} · ` +
|
|
646
|
+
`npm ${versions.npm ?? 'not found'} · ${versions.os.name} (${versions.os.release}) ${versions.os.arch}`);
|
|
647
|
+
lines.push(`${label('Node')}${versions.nodePath} (${versions.nodeKind})`);
|
|
648
|
+
lines.push(`${label('Running')}${versions.entryPath} (${versions.runKind})`);
|
|
649
|
+
lines.push(`${label('MCP')}${mcpText(report.desktopCommanderMcp)}`);
|
|
650
|
+
const ahead = clock.serverAheadSeconds;
|
|
651
|
+
lines.push(`${label('Clock')}${ahead === null ? `unknown (${clock.error})`
|
|
652
|
+
: Math.abs(ahead) <= 1 ? 'device matches the server (within 1 s, from the server\'s Date header)'
|
|
653
|
+
: `device is ${Math.abs(ahead)} s ${ahead > 0 ? 'behind' : 'ahead of'} the server (from the server's Date header)`}`);
|
|
654
|
+
const { server, supabase, proxy } = network;
|
|
655
|
+
const info = server.mcpInfo;
|
|
656
|
+
const infoText = info.ms.length
|
|
657
|
+
? `/api/mcp-info ${info.ms.length}× ${Math.min(...info.ms)}/${median(info.ms)}/${Math.max(...info.ms)} ms (min/median/max)` +
|
|
658
|
+
(info.statuses.some((s) => s !== 200) ? `, statuses ${info.statuses.join(', ')}` : '') +
|
|
659
|
+
(info.error ? `, then failed: ${info.error}` : '')
|
|
660
|
+
: `/api/mcp-info failed: ${info.error}`;
|
|
661
|
+
lines.push(`${label('Network')}${server.host}: ${[hostLine(server), infoText].filter(Boolean).join(' · ')}`);
|
|
662
|
+
if ('rest' in supabase) {
|
|
663
|
+
const rt = supabase.realtime;
|
|
664
|
+
const realtime = rt.openedMs === undefined
|
|
665
|
+
? `realtime websocket not opened (${rt.error})`
|
|
666
|
+
: `realtime websocket opened in ${rt.openedMs} ms, ${rt.heartbeat ? 'heartbeat answered' : `heartbeat ${rt.error}`}`;
|
|
667
|
+
lines.push(`${indent}Supabase: ${[hostLine(supabase), restText(supabase.rest), realtime].filter(Boolean).join(' · ')}`);
|
|
668
|
+
}
|
|
669
|
+
else {
|
|
670
|
+
lines.push(`${indent}Supabase: ${supabase.error}`);
|
|
671
|
+
}
|
|
672
|
+
lines.push(`${indent}Proxy: HTTPS_PROXY ${proxy.httpsProxy ? 'set' : 'not set'} · HTTP_PROXY ${proxy.httpProxy ? 'set' : 'not set'}`);
|
|
673
|
+
const saved = device.savedAt === null ? '' : `, saved ${utcMinute(device.savedAt)} UTC`;
|
|
674
|
+
lines.push(`${label('Device')}${!device.deviceJson ? 'signed-in data: no (no device.json)'
|
|
675
|
+
: !device.parses ? `signed-in data: device.json does not parse${saved}`
|
|
676
|
+
// Signed in means a token is really there, not just a session object
|
|
677
|
+
: `id ${device.id ?? 'none'} · signed-in data: ${yesNo(device.accessToken || device.refreshToken)} ` +
|
|
678
|
+
`(access token: ${yesNo(device.accessToken)}, refresh token: ${yesNo(device.refreshToken)})${saved}`}`);
|
|
679
|
+
const telemetry = config.telemetryEnabled === null ? 'not set' : config.telemetryEnabled ? 'on' : 'off';
|
|
680
|
+
lines.push(`${label('Settings')}telemetry: ${telemetry} · client id: ${config.clientId ?? 'none'}` +
|
|
681
|
+
(config.clientId ? ' (lets us find this device\'s telemetry)' : ''));
|
|
682
|
+
lines.push(`${label('Device log')}${log.lines === 0
|
|
683
|
+
? (log.files ? `${log.files} file(s), no lines` : 'none yet (it is written while `remote` runs)')
|
|
684
|
+
: `${log.lines.toLocaleString('en-US')} lines from ${utcMinute(log.first)} to ${utcMinute(log.last)} UTC; last: "${log.lastText}"`}`);
|
|
685
|
+
return lines.join('\n') + '\n';
|
|
686
|
+
}
|
|
687
|
+
function zipName(home, date) {
|
|
688
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
689
|
+
const stamp = `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}`;
|
|
690
|
+
for (let n = 1;; n++) {
|
|
691
|
+
const file = path.join(home, `desktop-commander-report-${stamp}${n > 1 ? `-${n}` : ''}.zip`);
|
|
692
|
+
if (!fs.existsSync(file))
|
|
693
|
+
return file;
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
/** Collects the report and writes the zip to the home folder; returns its bytes for the upload too. */
|
|
697
|
+
export async function writeReport() {
|
|
698
|
+
const { report, logParts, diagnosticsUrl } = await collectReport();
|
|
699
|
+
const zip = new PizZip();
|
|
700
|
+
zip.file('report.txt', formatReport(report));
|
|
701
|
+
zip.file('report.json', JSON.stringify(report, null, 2) + '\n');
|
|
702
|
+
for (const part of logParts)
|
|
703
|
+
zip.file(`device-log/${part.name}`, part.text);
|
|
704
|
+
const buffer = zip.generate({ type: 'nodebuffer', compression: 'DEFLATE', compressionOptions: { level: 6 } });
|
|
705
|
+
const file = zipName(os.homedir(), new Date(report.createdAt));
|
|
706
|
+
// Owner-only, like the device log
|
|
707
|
+
fs.writeFileSync(file, buffer, { flag: 'wx', mode: 0o600 });
|
|
708
|
+
return { file, bytes: buffer.length, zip: buffer, report, diagnosticsUrl };
|
|
709
|
+
}
|
|
710
|
+
/** `remote --report`: the terminal side. */
|
|
711
|
+
export async function runReport() {
|
|
712
|
+
console.log('Collecting diagnostics… (about 10 s)');
|
|
713
|
+
let result;
|
|
714
|
+
try {
|
|
715
|
+
result = await writeReport();
|
|
716
|
+
}
|
|
717
|
+
catch (error) {
|
|
718
|
+
console.error(`❌ Could not save the diagnostics report: ${errorText(error)}`);
|
|
719
|
+
process.exitCode = 1;
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
const { report, file, bytes, zip, diagnosticsUrl } = result;
|
|
723
|
+
const mark = (ok) => (ok ? '✓' : '✗');
|
|
724
|
+
const log = report.deviceLog;
|
|
725
|
+
console.log(' ' + [
|
|
726
|
+
`${mark(true)} versions`,
|
|
727
|
+
`${mark(report.clock.serverAheadSeconds !== null)} clock`,
|
|
728
|
+
`${mark(networkOk(report.network))} network`,
|
|
729
|
+
`${mark(true)} device state`,
|
|
730
|
+
// No log yet is a fact, not a failed check
|
|
731
|
+
`${mark(true)} device log (${log.files ? `${log.files} file${log.files === 1 ? '' : 's'}` : 'none yet'})`,
|
|
732
|
+
].join(' '));
|
|
733
|
+
console.log(`Saved: ${file} (${Math.max(1, Math.round(bytes / 1024))} KB)`);
|
|
734
|
+
console.log('It holds no passwords, tokens, emails or file contents; you can open it and check.');
|
|
735
|
+
if (process.argv.includes('--no-upload')) {
|
|
736
|
+
console.log('Reply to your support conversation with this file attached.');
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
try {
|
|
740
|
+
const id = await uploadReport(zip, { diagnosticsUrl, userId: savedUserId(os.homedir()), deviceId: report.device.id });
|
|
741
|
+
console.log(`Sent to Desktop Commander support. Report id: ${id}`);
|
|
742
|
+
console.log('Give this id to support. We keep it for 7 days, then delete it.');
|
|
743
|
+
}
|
|
744
|
+
catch (error) {
|
|
745
|
+
// The zip is saved either way
|
|
746
|
+
console.log(`Not sent (${errorText(error)}). Attach the zip to your support conversation instead.`);
|
|
747
|
+
}
|
|
748
|
+
}
|