-
Notifications
You must be signed in to change notification settings - Fork 3k
Expand file tree
/
Copy pathdoctorCommand.ts
More file actions
660 lines (596 loc) · 20.4 KB
/
Copy pathdoctorCommand.ts
File metadata and controls
660 lines (596 loc) · 20.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
/**
* @license
* Copyright 2025 Qwen
* SPDX-License-Identifier: Apache-2.0
*/
import type { CommandContext, SlashCommand } from './types.js';
import { CommandKind } from './types.js';
import type { HistoryItemDoctor } from '../types.js';
import { runDoctorChecks } from '../../utils/doctorChecks.js';
import {
collectMemoryPressureSamples,
formatMemoryDiagnostics,
formatMemoryPressureSamples,
getMemoryDiagnostics,
isHighHeapPressure,
writeMemoryHeapSnapshot,
} from '../../utils/memoryDiagnostics.js';
import {
isCpuProfileRecording,
startCpuProfile,
stopCpuProfile,
} from '../../utils/cpuProfiler.js';
import { rollbackStandaloneUpdate } from '../../utils/standalone-update.js';
import { getInstallationInfo } from '../../utils/installationInfo.js';
import { t } from '../../i18n/index.js';
import {
collectMemoryDiagnostics,
type MemoryDiagnostics,
} from '@qwen-code/qwen-code-core';
import { formatMemoryUsage } from '../utils/formatters.js';
const MEMORY_SUBCOMMAND = 'memory';
const CPU_PROFILE_SUBCOMMAND = 'cpu-profile';
const ROLLBACK_SUBCOMMAND = 'rollback';
const DOCTOR_SUBCOMMANDS = [MEMORY_SUBCOMMAND, CPU_PROFILE_SUBCOMMAND, ROLLBACK_SUBCOMMAND] as const;
function getHeapSnapshotSensitiveDataWarning(): string {
return t(
'Heap snapshot may contain prompts, file contents, tool results, and other sensitive data. Do not share it publicly without reviewing it first.',
);
}
function formatErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function formatHeapSnapshotErrorMessage(error: unknown): string {
const message = formatErrorMessage(error);
return message.startsWith('Heap snapshot')
? message
: `${t('Heap snapshot failed:')} ${message}`;
}
export const doctorCommand: SlashCommand = {
name: 'doctor',
get description() {
return t('Run installation and environment diagnostics');
},
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
argumentHint: '[memory|cpu-profile|rollback] [--sample] [--snapshot] [--duration]',
examples: [
'/doctor',
'/doctor memory',
'/doctor memory --sample',
'/doctor memory --snapshot',
'/doctor cpu-profile',
'/doctor cpu-profile --duration 10',
'/doctor rollback',
],
completion: async (_context, partialArg) => {
const trimmed = partialArg.trimStart();
return DOCTOR_SUBCOMMANDS.filter((candidate) =>
candidate.startsWith(trimmed),
);
},
action: async (context, args) => {
const executionMode = context.executionMode ?? 'interactive';
const abortSignal = context.abortSignal;
const subCommandArgs =
args?.trim().toLowerCase().split(/\s+/).filter(Boolean) ?? [];
const subCommand = subCommandArgs[0] ?? '';
const shouldWriteHeapSnapshot = subCommandArgs.includes('--snapshot');
const shouldSampleMemory = subCommandArgs.includes('--sample');
if (subCommand === ROLLBACK_SUBCOMMAND) {
if (executionMode === 'acp') {
return {
type: 'message' as const,
messageType: 'error' as const,
content: t('Rollback is not available in ACP mode.'),
};
}
return rollbackDoctorAction(context);
}
if (subCommand === MEMORY_SUBCOMMAND) {
if (abortSignal?.aborted) {
return;
}
const diagnostics = getMemoryDiagnostics();
if (abortSignal?.aborted) {
return;
}
let report = formatMemoryDiagnostics(diagnostics);
let messageType: 'info' | 'error' = 'info';
let heapSnapshotWritten = false;
if (abortSignal?.aborted) {
return;
}
if (shouldSampleMemory) {
const samples = await collectMemoryPressureSamples({
sampleCount: 3,
intervalMs: 1000,
signal: abortSignal,
});
report = `${report}\n\n${formatMemoryPressureSamples(samples)}`;
if (abortSignal?.aborted) {
if (executionMode === 'interactive') {
context.ui.addItem(
{
type: 'info',
text: report,
},
Date.now(),
);
return;
}
return {
type: 'message' as const,
messageType: 'info' as const,
content: report,
};
}
}
if (shouldWriteHeapSnapshot) {
if (abortSignal?.aborted) {
return;
}
if (executionMode === 'interactive') {
context.ui.setPendingItem({
type: 'info',
text: t('Writing heap snapshot, this may take a moment...'),
});
}
try {
const latestDiagnostics = shouldSampleMemory
? getMemoryDiagnostics()
: diagnostics;
if (isHighHeapPressure(latestDiagnostics)) {
throw new Error(
t(
'Heap snapshot skipped: V8 heap pressure is already high, and writing a synchronous heap snapshot could make the process unresponsive or trigger OOM. Restart Qwen Code first if it is unstable, or retry before memory pressure reaches the warning threshold.',
),
);
}
const heapSnapshotPath = writeMemoryHeapSnapshot();
heapSnapshotWritten = true;
report = `${report}\n\n${t('Heap snapshot written:')} ${heapSnapshotPath}\n${getHeapSnapshotSensitiveDataWarning()}`;
} catch (error) {
messageType = 'error';
report = `${report}\n\n${formatHeapSnapshotErrorMessage(error)}`;
} finally {
if (executionMode === 'interactive') {
context.ui.setPendingItem(null);
}
}
}
if (
abortSignal?.aborted &&
shouldWriteHeapSnapshot &&
!heapSnapshotWritten
) {
return;
}
if (executionMode === 'interactive') {
context.ui.addItem(
{
type: messageType === 'error' ? 'error' : 'info',
text: report,
},
Date.now(),
);
return;
}
return {
type: 'message' as const,
messageType,
content: report,
};
}
if (subCommand === CPU_PROFILE_SUBCOMMAND) {
return cpuProfileDoctorAction(context, subCommandArgs.slice(1).join(' '));
}
if (executionMode === 'interactive') {
context.ui.setPendingItem({
type: 'info',
text: t('Running diagnostics...'),
});
}
try {
const checks = await runDoctorChecks(context);
if (abortSignal?.aborted) {
return;
}
const summary = {
pass: checks.filter((c) => c.status === 'pass').length,
warn: checks.filter((c) => c.status === 'warn').length,
fail: checks.filter((c) => c.status === 'fail').length,
};
if (executionMode === 'interactive') {
const doctorItem: Omit<HistoryItemDoctor, 'id'> = {
type: 'doctor',
checks,
summary,
};
context.ui.addItem(doctorItem, Date.now());
return;
}
return {
type: 'message' as const,
messageType: (summary.fail > 0 ? 'error' : 'info') as 'error' | 'info',
content: JSON.stringify({ checks, summary }, null, 2),
};
} finally {
if (executionMode === 'interactive') {
context.ui.setPendingItem(null);
}
}
},
subCommands: [
{
name: 'memory',
get description() {
return t('Show current process memory diagnostics');
},
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
argumentHint: '[--json] [--sample] [--snapshot]',
action: memoryDoctorAction,
},
{
name: 'cpu-profile',
get description() {
return t('Record a CPU profile for Chrome DevTools analysis');
},
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive', 'acp'] as const,
argumentHint: '[--duration <seconds>]',
action: cpuProfileDoctorAction,
},
{
name: 'rollback',
get description() {
return t('Roll back a standalone update to the previous version');
},
kind: CommandKind.BUILT_IN,
supportedModes: ['interactive', 'non_interactive'] as const,
action: rollbackDoctorAction,
},
],
};
const MEMORY_USAGE_HINT = '/doctor memory [--json] [--sample] [--snapshot]';
async function memoryDoctorAction(context: CommandContext, args = '') {
if (context.abortSignal?.aborted) {
return;
}
const tokens = args.trim().split(/\s+/).filter(Boolean);
const unknown = tokens.filter(
(token) =>
token !== '--json' && token !== '--sample' && token !== '--snapshot',
);
if (unknown.length > 0) {
return {
type: 'message' as const,
messageType: 'error' as const,
content: `${t('Unknown argument(s)')}: ${unknown.join(', ')}. ${t('Usage')}: ${MEMORY_USAGE_HINT}`,
};
}
const shouldSampleMemory = tokens.includes('--sample');
const shouldWriteHeapSnapshot = tokens.includes('--snapshot');
if (shouldSampleMemory || shouldWriteHeapSnapshot) {
return doctorCommand.action?.(
context,
[MEMORY_SUBCOMMAND, ...tokens.filter((token) => token !== '--json')].join(
' ',
),
);
}
try {
const diagnostics = await collectMemoryDiagnostics({
sessionId: context.services.config?.getSessionId(),
qwenVersion: context.services.config?.getCliVersion(),
});
if (context.abortSignal?.aborted) {
return;
}
return {
type: 'message' as const,
messageType:
diagnostics.analysis.risks.length > 0
? ('warning' as const)
: ('info' as const),
content: tokens.includes('--json')
? JSON.stringify(diagnostics, null, 2)
: formatCoreDiagnostics(diagnostics),
};
} catch (error) {
if (context.abortSignal?.aborted) {
return;
}
return {
type: 'message' as const,
messageType: 'error' as const,
content: `${t('Failed to collect memory diagnostics')}: ${formatErrorMessage(error)}`,
};
}
}
// resourceUsage CPU times are microseconds; convert to seconds for display.
function formatCpuMicroseconds(micros: number): string {
return `${(micros / 1_000_000).toFixed(2)}s`;
}
function formatHeapSpaces(
spaces: MemoryDiagnostics['v8HeapSpaces'],
): string | undefined {
if (!spaces || spaces.length === 0) {
return undefined;
}
const top = [...spaces].sort((a, b) => b.used - a.used).slice(0, 4);
const lines = top.map(
(space) =>
` - ${space.name}: used ${formatMemoryUsage(space.used)} / size ${formatMemoryUsage(space.size)}`,
);
if (spaces.length > top.length) {
lines.push(` - … ${spaces.length - top.length} more`);
}
return lines.join('\n');
}
function formatSmapsRollup(smapsRollup: string | null): string {
if (!smapsRollup) {
return t('unavailable');
}
const rssLine = smapsRollup
.split(/\r?\n/)
.map((line) => line.trim().replace(/\s+/g, ' '))
.find((line) => line.startsWith('Rss:'));
if (rssLine) {
return rssLine;
}
const preview = smapsRollup.slice(0, 80).trim().replace(/\s+/g, ' ');
return `${t('parse error')}: ${preview}`;
}
function formatCoreDiagnostics(diagnostics: MemoryDiagnostics): string {
const risks =
diagnostics.analysis.risks.length > 0
? diagnostics.analysis.risks
.map((risk) => ` - ${risk.type}: ${risk.message}`)
.join('\n')
: ` ${t('none')}`;
const lines: string[] = [
t('Memory Diagnostics'),
`timestamp: ${diagnostics.timestamp}`,
`uptimeSeconds: ${diagnostics.uptimeSeconds.toFixed(1)}`,
`heapUsed: ${formatMemoryUsage(diagnostics.memoryUsage.heapUsed)}`,
`heapTotal: ${formatMemoryUsage(diagnostics.memoryUsage.heapTotal)}`,
`rss: ${formatMemoryUsage(diagnostics.memoryUsage.rss)}`,
`external: ${formatMemoryUsage(diagnostics.memoryUsage.external)}`,
`arrayBuffers: ${formatMemoryUsage(diagnostics.memoryUsage.arrayBuffers)}`,
`v8HeapLimit: ${formatMemoryUsage(diagnostics.v8HeapStats.heapSizeLimit)}`,
`v8MallocedMemory: ${formatMemoryUsage(diagnostics.v8HeapStats.mallocedMemory)}`,
`v8PeakMallocedMemory: ${formatMemoryUsage(diagnostics.v8HeapStats.peakMallocedMemory)}`,
`detachedContexts: ${diagnostics.v8HeapStats.detachedContexts}`,
`nativeContexts: ${diagnostics.v8HeapStats.nativeContexts}`,
`maxRSS: ${formatMemoryUsage(diagnostics.resourceUsage.maxRSS)}`,
`userCPUTime: ${formatCpuMicroseconds(diagnostics.resourceUsage.userCPUTime)}`,
`systemCPUTime: ${formatCpuMicroseconds(diagnostics.resourceUsage.systemCPUTime)}`,
`activeHandles: ${diagnostics.activeHandles}`,
`activeRequests: ${diagnostics.activeRequests}`,
`openFileDescriptors: ${diagnostics.openFileDescriptors ?? t('unavailable')}`,
`smapsRollup: ${formatSmapsRollup(diagnostics.smapsRollup)}`,
];
const heapSpaces = formatHeapSpaces(diagnostics.v8HeapSpaces);
if (heapSpaces) {
lines.push('v8HeapSpaces:', heapSpaces);
}
lines.push(
'risks:',
risks,
`recommendation: ${diagnostics.analysis.recommendation}`,
);
return lines.join('\n');
}
// ---------------------------------------------------------------------------
// /doctor cpu-profile
// ---------------------------------------------------------------------------
const CPU_PROFILE_USAGE_HINT = '/doctor cpu-profile [--duration <seconds>]';
const DEFAULT_CPU_PROFILE_DURATION_SEC = 30;
const MAX_CPU_PROFILE_DURATION_SEC = 300;
async function cpuProfileDoctorAction(
context: CommandContext,
args = '',
): Promise<void | {
type: 'message';
messageType: 'info' | 'error';
content: string;
}> {
const executionMode = context.executionMode ?? 'interactive';
const abortSignal = context.abortSignal;
if (abortSignal?.aborted) return;
const tokens = args.trim().split(/\s+/).filter(Boolean);
// Parse --duration flag
let durationSec = DEFAULT_CPU_PROFILE_DURATION_SEC;
const durationIdx = tokens.indexOf('--duration');
if (durationIdx !== -1) {
const rawVal = tokens[durationIdx + 1];
const val = rawVal ? parseInt(rawVal, 10) : NaN;
if (
!Number.isFinite(val) ||
val < 1 ||
val > MAX_CPU_PROFILE_DURATION_SEC
) {
const errorMsg = `${t('Duration must be between 1 and {max} seconds', { max: String(MAX_CPU_PROFILE_DURATION_SEC) })}. ${t('Usage')}: ${CPU_PROFILE_USAGE_HINT}`;
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: errorMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'error', content: errorMsg };
}
durationSec = val;
}
// Validate unknown arguments
const knownTokens = new Set(['--duration']);
const unknown = tokens.filter((token, idx) => {
if (knownTokens.has(token)) return false;
// Skip the value after --duration
if (idx > 0 && tokens[idx - 1] === '--duration') return false;
return true;
});
if (unknown.length > 0) {
const errorMsg = `${t('Unknown argument(s)')}: ${unknown.join(', ')}. ${t('Usage')}: ${CPU_PROFILE_USAGE_HINT}`;
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: errorMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'error', content: errorMsg };
}
// Check if already recording
if (isCpuProfileRecording()) {
const errorMsg =
process.platform === 'win32'
? t('CPU profiling is already in progress. Wait for it to complete.')
: t(
'CPU profiling is already in progress. Send SIGUSR1 or wait for it to complete.',
);
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: errorMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'error', content: errorMsg };
}
// Start recording
const startResult = await startCpuProfile();
if (!startResult.ok) {
if (executionMode === 'interactive') {
context.ui.addItem(
{ type: 'error', text: startResult.error },
Date.now(),
);
return;
}
return {
type: 'message',
messageType: 'error',
content: startResult.error,
};
}
if (abortSignal?.aborted) {
const abortResult = await stopCpuProfile();
if (abortResult.ok) {
const msg = t('CPU profile aborted early. Profile saved: {path}', {
path: abortResult.filePath,
});
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'info', text: msg }, Date.now());
}
} else {
const msg = `${t('CPU profile aborted but failed to stop cleanly')}: ${abortResult.error}`;
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: msg }, Date.now());
}
}
return;
}
// Show progress in interactive mode
if (executionMode === 'interactive') {
context.ui.setPendingItem({
type: 'info',
text: t('Recording CPU profile for {duration}s...', {
duration: String(durationSec),
}),
});
}
// Wait for duration or abort. Timer is NOT unref'd so non-interactive
// mode keeps the process alive for the full recording window.
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, durationSec * 1000);
if (abortSignal) {
abortSignal.addEventListener(
'abort',
() => {
clearTimeout(timer);
resolve();
},
{ once: true },
);
}
});
if (executionMode === 'interactive') {
context.ui.setPendingItem(null);
}
// Stop and write profile. If profiler is no longer recording (e.g., SIGUSR1
// stopped it during the wait), treat as success — the profile was already written.
const stopResult = await stopCpuProfile();
if (!stopResult.ok) {
const alreadyStopped = stopResult.error.includes('not recording');
if (alreadyStopped) {
const infoMsg =
process.platform === 'win32'
? t(
'CPU profile was stopped externally. Check ~/.qwen/cpu-profiles/ for the output.',
)
: t(
'CPU profile was stopped externally (e.g., via SIGUSR1). Check ~/.qwen/cpu-profiles/ for the output.',
);
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'info', text: infoMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'info', content: infoMsg };
}
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'error', text: stopResult.error }, Date.now());
return;
}
return { type: 'message', messageType: 'error', content: stopResult.error };
}
const successMsg = `${t('CPU profile written:')} ${stopResult.filePath}\n${t('Open in Chrome DevTools → Performance tab → Load profile')}`;
if (executionMode === 'interactive') {
context.ui.addItem({ type: 'info', text: successMsg }, Date.now());
return;
}
return { type: 'message', messageType: 'info', content: successMsg };
}
function rollbackDoctorAction(context: CommandContext) {
const installInfo = getInstallationInfo(process.cwd(), false);
if (!installInfo.isStandalone || !installInfo.standaloneDir) {
const msg = t('Rollback is only available for standalone installations.');
if (context.executionMode === 'interactive') {
context.ui.addItem({ type: 'info', text: msg }, Date.now());
return;
}
return {
type: 'message' as const,
messageType: 'info' as const,
content: msg,
};
}
if (process.platform === 'win32') {
const winMsg = t(
'Rollback on Windows requires manual intervention. Rename qwen-code.old to qwen-code in your installation directory.',
);
if (context.executionMode === 'interactive') {
context.ui.addItem({ type: 'info', text: winMsg }, Date.now());
return;
}
return {
type: 'message' as const,
messageType: 'info' as const,
content: winMsg,
};
}
const result = rollbackStandaloneUpdate(installInfo.standaloneDir);
let msg: string;
let messageType: 'info' | 'error';
if (result.ok) {
msg = t(
'Rollback successful. Restart your terminal to use the previous version.',
);
messageType = 'info';
} else {
msg = `${t('Rollback failed:')} ${result.detail}`;
messageType = 'error';
}
if (context.executionMode === 'interactive') {
context.ui.addItem({ type: messageType, text: msg }, Date.now());
return;
}
return {
type: 'message' as const,
messageType: messageType as 'info' | 'error',
content: msg,
};
}