-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcli.test.ts
More file actions
1260 lines (1110 loc) · 42 KB
/
Copy pathcli.test.ts
File metadata and controls
1260 lines (1110 loc) · 42 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
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2026 Qwen Team
* SPDX-License-Identifier: Apache-2.0
*/
import type { Argv } from 'yargs';
import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';
import {
chmodSync,
copyFileSync,
mkdirSync,
mkdtempSync,
readFileSync,
realpathSync,
renameSync,
rmSync,
statSync,
utimesSync,
writeFileSync,
} from 'node:fs';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { FatalError } from '@qwen-code/qwen-code-core';
import { AlreadyReportedError } from './utils/errors.js';
import {
MCP_COMMANDS,
TOP_LEVEL_COMMANDS,
handleCriticalError,
isExpectedPtyRaceError,
resolveBootstrapRoute,
runCliEntry,
runCliEntryPoint,
stampCliEntryEnv,
} from './cli.js';
const mocks = vi.hoisted(() => ({
main: vi.fn(),
tryRunServeFastPath: vi.fn(),
initStartupProfiler: vi.fn(),
initializeAcpStartupProfiler: vi.fn(),
markAcpStartup: vi.fn(),
initCpuProfiler: vi.fn(),
mcpHandler: vi.fn(),
mcpBuilder: vi.fn(),
mcpListHandler: vi.fn(),
mcpAddHandler: vi.fn(),
getCliVersion: vi.fn(),
installManagedNpmUpdate: vi.fn(),
}));
vi.mock('./gemini.js', () => ({
main: mocks.main,
}));
vi.mock('./serve/fast-path.js', () => ({
tryRunServeFastPath: mocks.tryRunServeFastPath,
}));
vi.mock('./utils/startupProfiler.js', () => ({
initStartupProfiler: mocks.initStartupProfiler,
}));
vi.mock('./utils/acp-startup-profiler.js', () => ({
initializeAcpStartupProfiler: mocks.initializeAcpStartupProfiler,
markAcpStartup: mocks.markAcpStartup,
}));
vi.mock('./utils/cpuProfiler.js', () => ({
initCpuProfiler: mocks.initCpuProfiler,
}));
vi.mock('./utils/version.js', () => ({
getCliVersion: mocks.getCliVersion,
}));
vi.mock('./utils/managed-npm-update.js', () => ({
installManagedNpmUpdate: mocks.installManagedNpmUpdate,
}));
vi.mock('./commands/mcp.js', () => ({
mcpCommand: {
command: 'mcp',
describe: 'Manage MCP servers',
builder: (yargs: Argv) => {
mocks.mcpBuilder();
return yargs
.command({
command: 'list',
describe: 'List all configured MCP servers',
handler: mocks.mcpListHandler,
})
.command({
command: 'add <name>',
describe: 'Add a server',
handler: mocks.mcpAddHandler,
})
.demandCommand(1, 'You need at least one command before continuing.');
},
handler: mocks.mcpHandler,
},
}));
describe('resolveBootstrapRoute', () => {
it('routes top-level help, version, serve, and mcp correctly', async () => {
expect(resolveBootstrapRoute(['--help'])).toBe('help');
expect(resolveBootstrapRoute(['--version'])).toBe('version');
expect(resolveBootstrapRoute(['mcp', '--version'])).toBe('version');
expect(resolveBootstrapRoute(['serve', '--help'])).toBe('serve');
expect(resolveBootstrapRoute(['mcp', '--help'])).toBe('mcp');
});
it('keeps bundled entrypoint paths out of the route detection', async () => {
expect(resolveBootstrapRoute(['/repo/dist/cli.js', '--help'])).toBe('help');
expect(
resolveBootstrapRoute(['C:\\repo\\dist\\cli.js', 'mcp', '--help']),
).toBe('mcp');
});
it('falls back to the default route for normal interactive startup', async () => {
expect(resolveBootstrapRoute([])).toBe('default');
expect(resolveBootstrapRoute(['--model', 'gpt-4', 'Hello'])).toBe(
'default',
);
expect(resolveBootstrapRoute(['--safe-mode', 'mcp', 'list'])).toBe(
'default',
);
});
it('does not treat values for global flags as positional commands or bootstrap flags', () => {
expect(resolveBootstrapRoute(['--model', 'gpt-4', '--help'])).toBe('help');
expect(resolveBootstrapRoute(['-p', 'hello', '--help'])).toBe('help');
expect(resolveBootstrapRoute(['--model', '-v'])).toBe('default');
});
it('does not treat flags after -- as bootstrap flags', () => {
expect(resolveBootstrapRoute(['--', '--version'])).toBe('default');
expect(resolveBootstrapRoute(['mcp', '--', '--version'])).toBe('mcp');
});
});
describe('runCliEntry', () => {
const savedEnv = {
CLI_VERSION: process.env['CLI_VERSION'],
QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN:
process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN'],
QWEN_CODE_MANAGED_NPM_UPDATE_VERSION:
process.env['QWEN_CODE_MANAGED_NPM_UPDATE_VERSION'],
};
let stdout: string[];
let stderr: string[];
let savedExitCode: string | number | null | undefined;
beforeEach(() => {
stdout = [];
stderr = [];
savedExitCode = process.exitCode;
process.exitCode = undefined;
vi.clearAllMocks();
mocks.tryRunServeFastPath.mockResolvedValue(false);
mocks.getCliVersion.mockResolvedValue('fallback-version');
process.env['CLI_VERSION'] = '9.9.9';
vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
stdout.push(String(chunk));
return true;
});
vi.spyOn(process.stderr, 'write').mockImplementation((chunk) => {
stderr.push(String(chunk));
return true;
});
});
afterEach(() => {
process.exitCode = savedExitCode;
if (savedEnv.CLI_VERSION === undefined) {
delete process.env['CLI_VERSION'];
} else {
process.env['CLI_VERSION'] = savedEnv.CLI_VERSION;
}
if (savedEnv.QWEN_CODE_MANAGED_NPM_UPDATE_VERSION === undefined) {
delete process.env['QWEN_CODE_MANAGED_NPM_UPDATE_VERSION'];
} else {
process.env['QWEN_CODE_MANAGED_NPM_UPDATE_VERSION'] =
savedEnv.QWEN_CODE_MANAGED_NPM_UPDATE_VERSION;
}
if (savedEnv.QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN === undefined) {
delete process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN'];
} else {
process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN'] =
savedEnv.QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN;
}
vi.restoreAllMocks();
});
it('prints the version without loading the full CLI graph', async () => {
await runCliEntry(['--version']);
expect(stdout.join('')).toContain('9.9.9');
expect(mocks.main).not.toHaveBeenCalled();
expect(mocks.tryRunServeFastPath).not.toHaveBeenCalled();
expect(mocks.initStartupProfiler).not.toHaveBeenCalled();
expect(mocks.initCpuProfiler).not.toHaveBeenCalled();
});
it('runs a managed update worker without starting the CLI', async () => {
process.env['QWEN_CODE_MANAGED_NPM_UPDATE_VERSION'] = '2.0.0';
process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN'] = 'guard-secret';
mocks.installManagedNpmUpdate.mockImplementationOnce(async () => {
expect(
process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN'],
).toBeUndefined();
});
await runCliEntry([]);
expect(mocks.installManagedNpmUpdate).toHaveBeenCalledWith('2.0.0');
expect(process.env['QWEN_CODE_MANAGED_NPM_UPDATE_VERSION']).toBeUndefined();
expect(mocks.main).not.toHaveBeenCalled();
});
it('falls back to getCliVersion when CLI_VERSION is unset', async () => {
delete process.env['CLI_VERSION'];
await runCliEntry(['--version']);
expect(stdout.join('')).toContain('fallback-version');
expect(mocks.getCliVersion).toHaveBeenCalledTimes(1);
expect(mocks.main).not.toHaveBeenCalled();
expect(mocks.tryRunServeFastPath).not.toHaveBeenCalled();
});
it('prints top-level help without loading the full CLI graph', async () => {
await runCliEntry(['--help']);
const helpText = stdout.join('');
expect(helpText).toContain('Usage: qwen [options] [command]');
expect(helpText).toContain('Manage Qwen Code hooks');
expect(helpText).toContain('Manage MCP servers');
expect(helpText).toContain('Run Qwen Code as a local HTTP daemon');
expect(helpText).toContain('--model');
expect(helpText).toContain('-p, --prompt');
expect(helpText).toContain('--safe-mode');
expect(helpText).toContain('-s, --sandbox');
expect(helpText).toContain('-o, --output-format');
expect(helpText).toContain('-r, --resume');
expect(mocks.main).not.toHaveBeenCalled();
expect(mocks.tryRunServeFastPath).not.toHaveBeenCalled();
expect(mocks.initStartupProfiler).not.toHaveBeenCalled();
expect(mocks.initCpuProfiler).not.toHaveBeenCalled();
});
it('routes the MCP help path without booting gemini', async () => {
await runCliEntry(['mcp', '--help']);
expect(stdout.join('')).toContain('Manage MCP servers');
expect(mocks.main).not.toHaveBeenCalled();
expect(mocks.tryRunServeFastPath).not.toHaveBeenCalled();
expect(mocks.initStartupProfiler).not.toHaveBeenCalled();
expect(mocks.initCpuProfiler).not.toHaveBeenCalled();
expect(mocks.mcpBuilder).not.toHaveBeenCalled();
});
it('does not execute MCP subcommands when showing subcommand help', async () => {
await runCliEntry(['mcp', 'list', '--help']);
const helpText = stdout.join('');
expect(helpText).toContain('List all configured MCP servers');
expect(mocks.mcpListHandler).not.toHaveBeenCalled();
expect(mocks.main).not.toHaveBeenCalled();
expect(mocks.initStartupProfiler).not.toHaveBeenCalled();
expect(mocks.initCpuProfiler).not.toHaveBeenCalled();
});
it('executes MCP subcommands through the fast path', async () => {
await runCliEntry(['mcp', 'list']);
expect(mocks.mcpListHandler).toHaveBeenCalledTimes(1);
expect(mocks.main).not.toHaveBeenCalled();
expect(mocks.initStartupProfiler).not.toHaveBeenCalled();
expect(mocks.initCpuProfiler).not.toHaveBeenCalled();
});
it('executes MCP subcommands after -- through the fast path', async () => {
await runCliEntry(['mcp', '--', 'list']);
expect(mocks.mcpListHandler).toHaveBeenCalledTimes(1);
expect(mocks.main).not.toHaveBeenCalled();
expect(mocks.initStartupProfiler).not.toHaveBeenCalled();
expect(mocks.initCpuProfiler).not.toHaveBeenCalled();
});
it('uses the full CLI when global flags precede MCP commands', async () => {
await runCliEntry(['--safe-mode', 'mcp', 'list']);
expect(mocks.main).toHaveBeenCalledTimes(1);
expect(mocks.mcpListHandler).not.toHaveBeenCalled();
});
it('fails MCP fast-path validation without loading the full CLI', async () => {
await runCliEntry(['mcp', 'doesnotexist']);
expect(process.exitCode).toBe(1);
expect(stderr.join('')).toContain('Unknown command: doesnotexist');
expect(mocks.mcpListHandler).not.toHaveBeenCalled();
expect(mocks.main).not.toHaveBeenCalled();
expect(mocks.initStartupProfiler).not.toHaveBeenCalled();
expect(mocks.initCpuProfiler).not.toHaveBeenCalled();
});
it('does not run MCP subcommands with unknown options', async () => {
await runCliEntry(['mcp', 'list', '--unknown']);
expect(process.exitCode).toBe(1);
expect(stderr.join('')).toContain('Unknown argument: unknown');
expect(mocks.mcpListHandler).not.toHaveBeenCalled();
expect(mocks.main).not.toHaveBeenCalled();
});
it('reports routine MCP argument errors without loading the full CLI', async () => {
await runCliEntry(['mcp', 'add']);
expect(process.exitCode).toBe(1);
expect(stderr.join('')).toContain('Not enough non-option arguments');
expect(mocks.mcpAddHandler).not.toHaveBeenCalled();
expect(mocks.main).not.toHaveBeenCalled();
});
it('keeps the serve fast path ahead of the full CLI startup', async () => {
mocks.tryRunServeFastPath.mockResolvedValue(true);
await runCliEntry(['serve']);
expect(mocks.tryRunServeFastPath).toHaveBeenCalledWith(['serve']);
expect(mocks.main).not.toHaveBeenCalled();
});
it('initializes profilers once when the serve fast path falls back', async () => {
mocks.tryRunServeFastPath.mockResolvedValue(false);
await runCliEntry(['serve']);
expect(mocks.tryRunServeFastPath).toHaveBeenCalledWith(['serve']);
expect(mocks.main).toHaveBeenCalledTimes(1);
});
it('preserves the external Guard token for the full serve parser', async () => {
process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN'] = 'guard-secret';
mocks.tryRunServeFastPath.mockResolvedValue(false);
mocks.main.mockImplementationOnce(async () => {
expect(process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN']).toBe(
'guard-secret',
);
});
await runCliEntry(['serve']);
expect(mocks.main).toHaveBeenCalledTimes(1);
});
it('scrubs the external Guard token before non-serve startup', async () => {
process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN'] = 'guard-secret';
mocks.main.mockImplementationOnce(async () => {
expect(
process.env['QWEN_CODE_EXTERNAL_TOOL_GUARD_TOKEN'],
).toBeUndefined();
});
await runCliEntry([]);
expect(mocks.main).toHaveBeenCalledTimes(1);
});
it('loads gemini on the default path', async () => {
await runCliEntry([]);
expect(mocks.main).toHaveBeenCalledTimes(1);
expect(mocks.initializeAcpStartupProfiler).not.toHaveBeenCalled();
});
it('profiles the Gemini module import only on the ACP path', async () => {
await runCliEntry(['--acp']);
expect(mocks.initializeAcpStartupProfiler).toHaveBeenCalledTimes(1);
expect(mocks.markAcpStartup.mock.calls).toEqual([
['geminiImportStart'],
['geminiImportEnd'],
]);
expect(mocks.main).toHaveBeenCalledTimes(1);
});
it('does not profile when ACP is explicitly disabled', async () => {
await runCliEntry(['--acp=false']);
expect(mocks.initializeAcpStartupProfiler).not.toHaveBeenCalled();
expect(mocks.markAcpStartup).not.toHaveBeenCalled();
expect(mocks.main).toHaveBeenCalledTimes(1);
});
});
describe('stampCliEntryEnv', () => {
// Isolated because the CLI exports QWEN_CODE_CLI to every shell it spawns —
// a test run started from inside a qwen session inherits it.
let originalCli: string | undefined;
let tempDir: string;
beforeEach(() => {
originalCli = process.env['QWEN_CODE_CLI'];
delete process.env['QWEN_CODE_CLI'];
tempDir = mkdtempSync(path.join(tmpdir(), 'qwen-entry-stamp-'));
});
afterEach(() => {
if (originalCli !== undefined) {
process.env['QWEN_CODE_CLI'] = originalCli;
} else {
delete process.env['QWEN_CODE_CLI'];
}
rmSync(tempDir, { recursive: true, force: true });
});
it('stamps the built bin entry so skill shell-outs reach THIS build', () => {
// A direct workspace launch (`node dist/index.js`) never passes through
// scripts/cli-entry.js, so without this stamp every
// `"${QWEN_CODE_CLI:-qwen}"` resolved a global install off PATH.
const entry = path.join(tempDir, 'index.js');
writeFileSync(entry, '#!/usr/bin/env node\nconsole.log("hi");\n');
stampCliEntryEnv(entry);
expect(process.env['QWEN_CODE_CLI']).toBe(entry);
});
it("never overwrites an outer launcher's stamp", () => {
// cli-entry.js may have selected a standalone shim, and the desktop app
// stamps its vendored bundle — both know launch details this module
// cannot see, and both run before runCliEntryPoint in the same process.
const entry = path.join(tempDir, 'index.js');
writeFileSync(entry, '#!/usr/bin/env node\n');
process.env['QWEN_CODE_CLI'] = '/outer/launcher/qwen';
stampCliEntryEnv(entry);
expect(process.env['QWEN_CODE_CLI']).toBe('/outer/launcher/qwen');
});
it('treats an inherited empty string as unset', () => {
// A parent session's spawn filter writes '' for an entry its shell could
// not exec. That verdict is about the parent's entry — this build must
// still stamp its own.
const entry = path.join(tempDir, 'index.js');
writeFileSync(entry, '#!/usr/bin/env node\n');
process.env['QWEN_CODE_CLI'] = '';
stampCliEntryEnv(entry);
expect(process.env['QWEN_CODE_CLI']).toBe(entry);
});
it.skipIf(process.platform === 'win32')(
'grants the execute bit tsc never emits, so the spawn filter passes the stamp',
() => {
// tsc writes dist/index.js as 0644 and only npm's bin-link chmods it; the
// spawn-time filter in core blanks a shebang-bearing entry without X_OK,
// which would turn this stamp into a no-op on every plain-build checkout.
const entry = path.join(tempDir, 'index.js');
writeFileSync(entry, '#!/usr/bin/env node\n', { mode: 0o644 });
stampCliEntryEnv(entry);
expect(process.env['QWEN_CODE_CLI']).toBe(entry);
expect(statSync(entry).mode & 0o111).not.toBe(0);
},
);
it('leaves the slot unset when the derived entry does not exist', () => {
stampCliEntryEnv(path.join(tempDir, 'no', 'such', 'index.js'));
expect(process.env['QWEN_CODE_CLI']).toBeUndefined();
});
it('derives the bin entry one level up from the compiled module', () => {
// cli.ts emits to dist/src/cli.js and the shebang bin is dist/index.js —
// one level up, not two. Two lands on the unbuilt packages/cli/index.js,
// which fails the existence check and silently never stamps, and no other
// test can catch that: the derivation is only reachable under a built
// layout, where vitest never runs.
const source = readFileSync('src/cli.ts', 'utf8');
expect(source).toContain("new URL('../index.js', import.meta.url)");
expect(
new URL('../index.js', 'file:///repo/packages/cli/dist/src/cli.js')
.pathname,
).toBe('/repo/packages/cli/dist/index.js');
});
it('default derivation never throws and never stamps outside a built layout', () => {
// Under vitest Vite rewrites new URL(…, import.meta.url) to a non-file
// URL, and in dev runs the derived ../index.js is the unbuilt
// packages/cli/index.js. Both must keep the bare-`qwen` fallback — a
// failed derivation taking the CLI down would be worse than the version
// skew this stamp exists to fix.
stampCliEntryEnv();
expect(process.env['QWEN_CODE_CLI']).toBeUndefined();
});
});
describe('bootstrap import boundaries', () => {
it('keeps fast-path-only dependencies out of static imports', () => {
const source = readFileSync('src/cli.ts', 'utf8');
expect(source).not.toContain("import yargs from 'yargs'");
expect(source).not.toContain("from '@qwen-code/qwen-code-core'");
expect(source).not.toContain("import './gemini.js'");
expect(source).not.toContain("import { main } from './gemini.js'");
expect(source).not.toContain("from './utils/acp-startup-profiler.js'");
});
it('initializes profilers during bootstrap module evaluation', () => {
const source = readFileSync('src/cli.ts', 'utf8');
expect(source).toContain(
"import { initStartupProfiler } from './utils/startupProfiler.js'",
);
expect(source).toContain(
"import { initCpuProfiler } from './utils/cpuProfiler.js'",
);
expect(source.indexOf('initStartupProfiler();')).toBeLessThan(
source.indexOf('export async function runCliEntry('),
);
expect(source.indexOf('initCpuProfiler();')).toBeLessThan(
source.indexOf('export async function runCliEntry('),
);
});
it('uses the bootstrap file as the production bundle entry', () => {
const source = readFileSync('../../esbuild.config.js', 'utf8');
expect(source).toContain("entryPoints: { cli: 'packages/cli/src/cli.ts' }");
});
it('keeps bootstrap fast paths in-process in the npm bin wrapper', () => {
const source = readFileSync('../../scripts/cli-entry.js', 'utf8');
expect(source).toContain('function isInProcessFastPath()');
expect(source).toContain("first === 'serve'");
expect(source).toContain("first === 'mcp'");
expect(source).toContain("hasFlag('--help', '-h')");
expect(source).toContain("hasFlag('--version', '-v')");
expect(source).toContain('UPDATE_COMPLETE_EXIT_CODE = 44');
});
it('publishes the daemon compile cache without overriding user policy', () => {
const tempDir = mkdtempSync(path.join(tmpdir(), 'qwen-compile-cache-'));
const entryPath = path.join(tempDir, 'cli-entry.mjs');
const unsupportedEntryPath = path.join(
tempDir,
'unsupported-cli-entry.mjs',
);
const probeEntryPath = path.join(tempDir, 'compile-cache-probe.mjs');
try {
copyFileSync('../../scripts/cli-entry.js', entryPath);
writeFileSync(
unsupportedEntryPath,
readFileSync('../../scripts/cli-entry.js', 'utf8').replace(
"const { default: module } = await import('node:module');",
'const module = {};',
),
);
writeFileSync(
probeEntryPath,
[
"import module from 'node:module';",
'const result = module.enableCompileCache?.();',
'process.stdout.write(JSON.stringify(Boolean(',
' result?.status === module.constants?.compileCacheStatus?.ENABLED &&',
' result?.directory,',
')));',
].join('\n'),
);
writeFileSync(
path.join(tempDir, 'cli.js'),
[
'process.stdout.write(JSON.stringify({',
' cacheDir: process.env.NODE_COMPILE_CACHE,',
' pendingCacheDir: process.env.QWEN_CODE_PENDING_COMPILE_CACHE,',
'}));',
].join('\n'),
);
const baseEnv = { ...process.env };
delete baseEnv['NODE_COMPILE_CACHE'];
delete baseEnv['NODE_DISABLE_COMPILE_CACHE'];
const runEntry = (
env: NodeJS.ProcessEnv,
args: string[] = ['serve'],
selectedEntryPath = entryPath,
) =>
JSON.parse(
execFileSync(process.execPath, [selectedEntryPath, ...args], {
encoding: 'utf8',
env,
}),
);
const canEnableCompileCache = JSON.parse(
execFileSync(process.execPath, [probeEntryPath], {
encoding: 'utf8',
env: baseEnv,
}),
);
if (canEnableCompileCache) {
expect(runEntry(baseEnv)).toEqual({
pendingCacheDir: expect.any(String),
});
} else {
expect(runEntry(baseEnv)).toEqual({});
}
expect(runEntry(baseEnv, ['serve'], unsupportedEntryPath)).toEqual({});
expect(runEntry(baseEnv, ['mcp', 'list'])).toEqual({});
const configuredCacheDir = path.join(tempDir, 'configured-cache');
expect(
runEntry({
...baseEnv,
NODE_COMPILE_CACHE: configuredCacheDir,
}),
).toEqual({ cacheDir: configuredCacheDir });
expect(
runEntry({
...baseEnv,
NODE_DISABLE_COMPILE_CACHE: '1',
}),
).toEqual({});
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
it.skipIf(process.platform === 'win32')(
'reloads the CLI through a stable shim after an update',
() => {
const tempDir = mkdtempSync(path.join(tmpdir(), 'qwen-cli-update-'));
const wrongDir = mkdtempSync(path.join(tmpdir(), 'qwen-cli-wrong-'));
const oldDir = path.join(tempDir, 'old');
const newDir = path.join(tempDir, 'new');
const binPath = path.join(tempDir, 'qwen');
try {
mkdirSync(oldDir);
mkdirSync(newDir);
copyFileSync(
'../../scripts/cli-entry.js',
path.join(oldDir, 'entry.mjs'),
);
copyFileSync(
'../../scripts/cli-entry.js',
path.join(newDir, 'entry.mjs'),
);
writeFileSync(
path.join(oldDir, 'cli.js'),
`import { chmodSync, rmSync, writeFileSync } from 'node:fs';\nwriteFileSync(${JSON.stringify(binPath)}, ${JSON.stringify(`#!/bin/sh\nexec "${process.execPath}" "${path.join(newDir, 'entry.mjs')}" "$@"\n`)});\nchmodSync(${JSON.stringify(binPath)}, 0o755);\nrmSync(${JSON.stringify(oldDir)}, { recursive: true, force: true });\nprocess.exit(44);\n`,
);
writeFileSync(
path.join(newDir, 'cli.js'),
"process.stdout.write(`${JSON.stringify({ args: process.argv.slice(2), skip: process.env.QWEN_CODE_SKIP_UPDATE_CHECK_ONCE, hasLauncherPid: /^\\d+$/.test(process.env.QWEN_CODE_LAUNCHER_PID ?? ''), launcherPath: process.env.QWEN_CODE_LAUNCHER_PATH })}\\n`);\n",
);
writeFileSync(
binPath,
`#!/bin/sh\nexec "${process.execPath}" "${path.join(oldDir, 'entry.mjs')}" "$@"\n`,
);
chmodSync(binPath, 0o755);
writeFileSync(
path.join(wrongDir, 'qwen'),
'#!/bin/sh\necho wrong-launcher\n',
);
chmodSync(path.join(wrongDir, 'qwen'), 0o755);
const output = execFileSync(binPath, ['--prompt', 'a&b'], {
encoding: 'utf8',
env: {
...process.env,
PATH: `${wrongDir}${path.delimiter}${tempDir}${path.delimiter}${process.env['PATH'] ?? ''}`,
},
});
expect(JSON.parse(output)).toEqual({
args: ['--prompt', 'a&b'],
skip: 'true',
hasLauncherPid: true,
});
} finally {
rmSync(tempDir, { recursive: true, force: true });
rmSync(wrongDir, { recursive: true, force: true });
}
},
);
it('does not pass the standalone launcher hint to child processes', () => {
const tempDir = mkdtempSync(path.join(tmpdir(), 'qwen-cli-launcher-env-'));
const entryPath = path.join(tempDir, 'entry.mjs');
const launcherPath = path.join(tempDir, 'qwen');
try {
copyFileSync('../../scripts/cli-entry.js', entryPath);
writeFileSync(
path.join(tempDir, 'cli.js'),
'process.stdout.write(JSON.stringify({ launcherPath: process.env.QWEN_CODE_LAUNCHER_PATH }));\n',
);
writeFileSync(launcherPath, '#!/bin/sh\n');
chmodSync(launcherPath, 0o755);
const output = execFileSync(process.execPath, [entryPath], {
encoding: 'utf8',
env: {
...process.env,
QWEN_CODE_LAUNCHER_PATH: launcherPath,
},
});
expect(JSON.parse(output)).toEqual({});
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
});
it('ignores malformed relaunch args in the npm bin wrapper', () => {
const output = execFileSync(
process.execPath,
['../../scripts/cli-entry.js', '--version'],
{
encoding: 'utf8',
env: { ...process.env, QWEN_CODE_RELAUNCH_ARGS: 'not-json' },
},
);
expect(output.trim()).toMatch(/^\d+\.\d+\.\d+/);
});
it('prints CLI_VERSION from the npm bin wrapper version shortcut', () => {
const output = execFileSync(
process.execPath,
['../../scripts/cli-entry.js', '--version'],
{
encoding: 'utf8',
env: { ...process.env, CLI_VERSION: '7.7.7-test' },
},
);
expect(output).toBe('7.7.7-test\n');
});
it('reads package.json from the npm bin wrapper version shortcut', () => {
const expectedVersion = JSON.parse(
readFileSync('../../package.json', 'utf8'),
).version;
const env = { ...process.env };
delete env['CLI_VERSION'];
const output = execFileSync(
process.execPath,
['../../scripts/cli-entry.js', '--version'],
{
encoding: 'utf8',
env,
},
);
expect(output).toBe(`${expectedVersion}\n`);
});
it('resolves and pins managed updates from the configured home', () => {
const tempDir = mkdtempSync(path.join(tmpdir(), 'qwen-managed-npm-'));
const entryDir = path.join(tempDir, 'bootstrap');
const entryPath = path.join(entryDir, 'cli-entry.mjs');
const qwenHome = path.join(tempDir, 'custom', 'qwen');
try {
mkdirSync(entryDir, { recursive: true });
copyFileSync('../../scripts/cli-entry.js', entryPath);
const bootstrapId = createHash('sha256')
.update(realpathSync(entryPath))
.digest('hex')
.slice(0, 16);
const launcherRoot = path.join(qwenHome, 'updates', 'npm', bootstrapId);
const packageRoot = path.join(
launcherRoot,
'versions',
'2.0.0',
'node_modules',
'@qwen-code',
'qwen-code',
);
mkdirSync(packageRoot, { recursive: true });
writeFileSync(
path.join(entryDir, 'cli.js'),
"process.stdout.write(JSON.stringify({ build: 'base', pin: process.env.QWEN_CODE_MANAGED_NPM_PIN }));\n",
);
writeFileSync(
path.join(entryDir, 'package.json'),
JSON.stringify({
name: '@qwen-code/qwen-code',
version: '1.0.0',
}),
);
writeFileSync(
path.join(packageRoot, 'package.json'),
JSON.stringify({
name: '@qwen-code/qwen-code',
version: '2.0.0',
}),
);
writeFileSync(
path.join(packageRoot, 'cli.js'),
"process.stdout.write(JSON.stringify({ build: 'managed-2', managed: process.env.QWEN_CODE_MANAGED_NPM_UPDATE, launcher: process.env.QWEN_CODE_CLI, pin: process.env.QWEN_CODE_MANAGED_NPM_PIN, args: process.argv.slice(2) }));\n",
);
mkdirSync(launcherRoot, { recursive: true });
const bootstrapStat = statSync(entryPath);
mkdirSync(path.join(tempDir, '.qwen'), { recursive: true });
writeFileSync(
path.join(tempDir, '.qwen', '.env'),
'\uFEFFQWEN_HOME: ~\\custom\\qwen\n',
);
const childEnv: NodeJS.ProcessEnv = {
...process.env,
HOME: tempDir,
USERPROFILE: tempDir,
TMPDIR: tempDir,
TEMP: tempDir,
TMP: tempDir,
};
delete childEnv['QWEN_HOME'];
delete childEnv['QWEN_CODE_MANAGED_NPM_PIN'];
const baseSession = JSON.parse(
execFileSync(process.execPath, [entryPath, '--prompt', 'hello'], {
encoding: 'utf8',
env: childEnv,
}),
) as { build: string; pin: string };
expect(baseSession.build).toBe('base');
writeFileSync(
path.join(launcherRoot, 'active.json'),
JSON.stringify({
version: '2.0.0',
bootstrap: realpathSync(entryPath),
baseVersion: '1.0.0',
bootstrapCtimeMs: bootstrapStat.ctimeMs,
}),
);
expect(
JSON.parse(
execFileSync(process.execPath, [entryPath, '--prompt', 'hello'], {
encoding: 'utf8',
env: {
...childEnv,
QWEN_CODE_MANAGED_NPM_PIN: baseSession.pin,
},
}),
),
).toMatchObject({ build: 'base' });
expect(
JSON.parse(
execFileSync(process.execPath, [entryPath, '--prompt', 'hello'], {
encoding: 'utf8',
env: { ...childEnv, QWEN_HOME: '' },
}),
),
).toMatchObject({ build: 'base' });
writeFileSync(
path.join(tempDir, '.qwen', '.env'),
`QWEN_HOME:${qwenHome}\n`,
);
expect(
JSON.parse(
execFileSync(process.execPath, [entryPath, '--prompt', 'hello'], {
encoding: 'utf8',
env: childEnv,
}),
),
).toMatchObject({ build: 'base' });
writeFileSync(
path.join(tempDir, '.qwen', '.env'),
`QWEN_HOME: \nOTHER=${qwenHome}\n`,
);
expect(
JSON.parse(
execFileSync(process.execPath, [entryPath, '--prompt', 'hello'], {
encoding: 'utf8',
env: childEnv,
}),
),
).toMatchObject({ build: 'base' });
writeFileSync(
path.join(tempDir, '.qwen', '.env'),
'\uFEFFQWEN_HOME: ~\\custom\\qwen\n',
);
const output = execFileSync(
process.execPath,
[entryPath, '--prompt', 'hello'],
{
encoding: 'utf8',
env: childEnv,
},
);
const managedSession = JSON.parse(output) as {
build: string;
managed: string;
launcher: string;
pin: string;
args: string[];
};
expect(managedSession).toMatchObject({
build: 'managed-2',
managed: 'true',
launcher: realpathSync(entryPath),
args: ['--prompt', 'hello'],
});
writeFileSync(
path.join(launcherRoot, 'active.json'),
JSON.stringify({
version: '3.0.0',
bootstrap: realpathSync(entryPath),
baseVersion: '1.0.0',
bootstrapCtimeMs: bootstrapStat.ctimeMs,
}),
);
expect(
JSON.parse(
execFileSync(process.execPath, [entryPath, '--prompt', 'hello'], {
encoding: 'utf8',
env: {
...childEnv,
QWEN_HOME: 'different-relative-home',
QWEN_CODE_MANAGED_NPM_PIN: managedSession.pin,
},
}),
),
).toMatchObject({ build: 'managed-2' });
writeFileSync(
path.join(launcherRoot, 'active.json'),
JSON.stringify({
version: '2.0.0',
bootstrap: realpathSync(entryPath),
baseVersion: '1.0.0',
bootstrapCtimeMs: bootstrapStat.ctimeMs,
}),
);
const emptyHomeRoot = path.join(tempDir, 'empty-home');
const emptyQwenHome = path.join(emptyHomeRoot, '.qwen');
mkdirSync(emptyQwenHome, { recursive: true });
renameSync(
path.join(qwenHome, 'updates'),
path.join(emptyQwenHome, 'updates'),
);
const emptyHomeEnv = {
...childEnv,
HOME: '',
USERPROFILE: '',
HOMEDRIVE: '',
HOMEPATH: '',
TMPDIR: emptyHomeRoot,
TEMP: emptyHomeRoot,
TMP: emptyHomeRoot,
};
expect(
JSON.parse(
execFileSync(process.execPath, [entryPath, '--prompt', 'hello'], {
encoding: 'utf8',
env: emptyHomeEnv,
}),
),
).toMatchObject({
build: 'managed-2',
managed: 'true',
launcher: realpathSync(entryPath),
args: ['--prompt', 'hello'],
});
const replacement = `${entryPath}.replacement`;
copyFileSync(entryPath, replacement);
renameSync(replacement, entryPath);
utimesSync(entryPath, bootstrapStat.atime, bootstrapStat.mtime);
expect(statSync(entryPath).ctimeMs).not.toBe(bootstrapStat.ctimeMs);
expect(
JSON.parse(
execFileSync(process.execPath, [entryPath, '--prompt', 'hello'], {
encoding: 'utf8',
env: emptyHomeEnv,
}),
),
).toMatchObject({ build: 'base' });
writeFileSync(
path.join(entryDir, 'package.json'),
JSON.stringify({
name: '@qwen-code/qwen-code',