ADAPT-Chase commited on
Commit
dc006ad
·
verified ·
1 Parent(s): 63aeb6a

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/cli/src/ui/commands/helpCommand.test.ts +52 -0
  2. projects/ui/qwen-code/packages/cli/src/ui/commands/helpCommand.ts +23 -0
  3. projects/ui/qwen-code/packages/cli/src/ui/commands/ideCommand.test.ts +255 -0
  4. projects/ui/qwen-code/packages/cli/src/ui/commands/ideCommand.ts +283 -0
  5. projects/ui/qwen-code/packages/cli/src/ui/commands/initCommand.test.ts +127 -0
  6. projects/ui/qwen-code/packages/cli/src/ui/commands/initCommand.ts +117 -0
  7. projects/ui/qwen-code/packages/cli/src/ui/commands/mcpCommand.test.ts +1057 -0
  8. projects/ui/qwen-code/packages/cli/src/ui/commands/mcpCommand.ts +531 -0
  9. projects/ui/qwen-code/packages/cli/src/ui/commands/memoryCommand.test.ts +344 -0
  10. projects/ui/qwen-code/packages/cli/src/ui/commands/memoryCommand.ts +305 -0
  11. projects/ui/qwen-code/packages/cli/src/ui/commands/privacyCommand.test.ts +38 -0
  12. projects/ui/qwen-code/packages/cli/src/ui/commands/privacyCommand.ts +17 -0
  13. projects/ui/qwen-code/packages/cli/src/ui/commands/quitCommand.test.ts +55 -0
  14. projects/ui/qwen-code/packages/cli/src/ui/commands/quitCommand.ts +36 -0
  15. projects/ui/qwen-code/packages/cli/src/ui/commands/restoreCommand.test.ts +250 -0
  16. projects/ui/qwen-code/packages/cli/src/ui/commands/restoreCommand.ts +157 -0
  17. projects/ui/qwen-code/packages/cli/src/ui/commands/settingsCommand.test.ts +36 -0
  18. projects/ui/qwen-code/packages/cli/src/ui/commands/settingsCommand.ts +17 -0
  19. projects/ui/qwen-code/packages/cli/src/ui/commands/setupGithubCommand.test.ts +238 -0
  20. projects/ui/qwen-code/packages/cli/src/ui/commands/setupGithubCommand.ts +212 -0
projects/ui/qwen-code/packages/cli/src/ui/commands/helpCommand.test.ts ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { helpCommand } from './helpCommand.js';
9
+ import { type CommandContext } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+ import { MessageType } from '../types.js';
12
+ import { CommandKind } from './types.js';
13
+
14
+ describe('helpCommand', () => {
15
+ let mockContext: CommandContext;
16
+ const originalEnv = { ...process.env };
17
+
18
+ beforeEach(() => {
19
+ mockContext = createMockCommandContext({
20
+ ui: {
21
+ addItem: vi.fn(),
22
+ },
23
+ } as unknown as CommandContext);
24
+ });
25
+
26
+ afterEach(() => {
27
+ process.env = { ...originalEnv };
28
+ vi.clearAllMocks();
29
+ });
30
+
31
+ it('should add a help message to the UI history', async () => {
32
+ if (!helpCommand.action) {
33
+ throw new Error('Help command has no action');
34
+ }
35
+
36
+ await helpCommand.action(mockContext, '');
37
+
38
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
39
+ expect.objectContaining({
40
+ type: MessageType.HELP,
41
+ timestamp: expect.any(Date),
42
+ }),
43
+ expect.any(Number),
44
+ );
45
+ });
46
+
47
+ it('should have the correct command properties', () => {
48
+ expect(helpCommand.name).toBe('help');
49
+ expect(helpCommand.kind).toBe(CommandKind.BUILT_IN);
50
+ expect(helpCommand.description).toBe('for help on Qwen Code');
51
+ });
52
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/helpCommand.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { CommandKind, SlashCommand } from './types.js';
8
+ import { MessageType, type HistoryItemHelp } from '../types.js';
9
+
10
+ export const helpCommand: SlashCommand = {
11
+ name: 'help',
12
+ altNames: ['?'],
13
+ kind: CommandKind.BUILT_IN,
14
+ description: 'for help on Qwen Code',
15
+ action: async (context) => {
16
+ const helpItem: Omit<HistoryItemHelp, 'id'> = {
17
+ type: MessageType.HELP,
18
+ timestamp: new Date(),
19
+ };
20
+
21
+ context.ui.addItem(helpItem, Date.now());
22
+ },
23
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/ideCommand.test.ts ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ MockInstance,
9
+ vi,
10
+ describe,
11
+ it,
12
+ expect,
13
+ beforeEach,
14
+ afterEach,
15
+ } from 'vitest';
16
+ import { ideCommand } from './ideCommand.js';
17
+ import { type CommandContext } from './types.js';
18
+ import { type Config, DetectedIde } from '@qwen-code/qwen-code-core';
19
+ import * as core from '@qwen-code/qwen-code-core';
20
+
21
+ vi.mock('child_process');
22
+ vi.mock('glob');
23
+ vi.mock('@qwen-code/qwen-code-core');
24
+
25
+ describe('ideCommand', () => {
26
+ let mockContext: CommandContext;
27
+ let mockConfig: Config;
28
+ let platformSpy: MockInstance;
29
+
30
+ beforeEach(() => {
31
+ mockContext = {
32
+ ui: {
33
+ addItem: vi.fn(),
34
+ },
35
+ services: {
36
+ settings: {
37
+ setValue: vi.fn(),
38
+ },
39
+ },
40
+ } as unknown as CommandContext;
41
+
42
+ mockConfig = {
43
+ getIdeMode: vi.fn(),
44
+ getIdeClient: vi.fn(() => ({
45
+ reconnect: vi.fn(),
46
+ disconnect: vi.fn(),
47
+ getCurrentIde: vi.fn(),
48
+ getDetectedIdeDisplayName: vi.fn(),
49
+ getConnectionStatus: vi.fn(),
50
+ })),
51
+ setIdeModeAndSyncConnection: vi.fn(),
52
+ setIdeMode: vi.fn(),
53
+ } as unknown as Config;
54
+
55
+ platformSpy = vi.spyOn(process, 'platform', 'get');
56
+ });
57
+
58
+ afterEach(() => {
59
+ vi.restoreAllMocks();
60
+ });
61
+
62
+ it('should return null if config is not provided', () => {
63
+ const command = ideCommand(null);
64
+ expect(command).toBeNull();
65
+ });
66
+
67
+ it('should return the ide command', () => {
68
+ vi.mocked(mockConfig.getIdeMode).mockReturnValue(true);
69
+ vi.mocked(mockConfig.getIdeClient).mockReturnValue({
70
+ getCurrentIde: () => DetectedIde.VSCode,
71
+ getDetectedIdeDisplayName: () => 'VS Code',
72
+ getConnectionStatus: () => ({
73
+ status: core.IDEConnectionStatus.Disconnected,
74
+ }),
75
+ } as ReturnType<Config['getIdeClient']>);
76
+ const command = ideCommand(mockConfig);
77
+ expect(command).not.toBeNull();
78
+ expect(command?.name).toBe('ide');
79
+ expect(command?.subCommands).toHaveLength(3);
80
+ expect(command?.subCommands?.[0].name).toBe('enable');
81
+ expect(command?.subCommands?.[1].name).toBe('status');
82
+ expect(command?.subCommands?.[2].name).toBe('install');
83
+ });
84
+
85
+ it('should show disable command when connected', () => {
86
+ vi.mocked(mockConfig.getIdeMode).mockReturnValue(true);
87
+ vi.mocked(mockConfig.getIdeClient).mockReturnValue({
88
+ getCurrentIde: () => DetectedIde.VSCode,
89
+ getDetectedIdeDisplayName: () => 'VS Code',
90
+ getConnectionStatus: () => ({
91
+ status: core.IDEConnectionStatus.Connected,
92
+ }),
93
+ } as ReturnType<Config['getIdeClient']>);
94
+ const command = ideCommand(mockConfig);
95
+ expect(command).not.toBeNull();
96
+ const subCommandNames = command?.subCommands?.map((cmd) => cmd.name);
97
+ expect(subCommandNames).toContain('disable');
98
+ expect(subCommandNames).not.toContain('enable');
99
+ });
100
+
101
+ describe('status subcommand', () => {
102
+ const mockGetConnectionStatus = vi.fn();
103
+ beforeEach(() => {
104
+ vi.mocked(mockConfig.getIdeClient).mockReturnValue({
105
+ getConnectionStatus: mockGetConnectionStatus,
106
+ getCurrentIde: () => DetectedIde.VSCode,
107
+ getDetectedIdeDisplayName: () => 'VS Code',
108
+ } as unknown as ReturnType<Config['getIdeClient']>);
109
+ });
110
+
111
+ it('should show connected status', async () => {
112
+ mockGetConnectionStatus.mockReturnValue({
113
+ status: core.IDEConnectionStatus.Connected,
114
+ });
115
+ const command = ideCommand(mockConfig);
116
+ const result = await command!.subCommands!.find(
117
+ (c) => c.name === 'status',
118
+ )!.action!(mockContext, '');
119
+ expect(mockGetConnectionStatus).toHaveBeenCalled();
120
+ expect(result).toEqual({
121
+ type: 'message',
122
+ messageType: 'info',
123
+ content: '🟢 Connected to VS Code',
124
+ });
125
+ });
126
+
127
+ it('should show connecting status', async () => {
128
+ mockGetConnectionStatus.mockReturnValue({
129
+ status: core.IDEConnectionStatus.Connecting,
130
+ });
131
+ const command = ideCommand(mockConfig);
132
+ const result = await command!.subCommands!.find(
133
+ (c) => c.name === 'status',
134
+ )!.action!(mockContext, '');
135
+ expect(mockGetConnectionStatus).toHaveBeenCalled();
136
+ expect(result).toEqual({
137
+ type: 'message',
138
+ messageType: 'info',
139
+ content: `🟡 Connecting...`,
140
+ });
141
+ });
142
+ it('should show disconnected status', async () => {
143
+ mockGetConnectionStatus.mockReturnValue({
144
+ status: core.IDEConnectionStatus.Disconnected,
145
+ });
146
+ const command = ideCommand(mockConfig);
147
+ const result = await command!.subCommands!.find(
148
+ (c) => c.name === 'status',
149
+ )!.action!(mockContext, '');
150
+ expect(mockGetConnectionStatus).toHaveBeenCalled();
151
+ expect(result).toEqual({
152
+ type: 'message',
153
+ messageType: 'error',
154
+ content: `🔴 Disconnected`,
155
+ });
156
+ });
157
+
158
+ it('should show disconnected status with details', async () => {
159
+ const details = 'Something went wrong';
160
+ mockGetConnectionStatus.mockReturnValue({
161
+ status: core.IDEConnectionStatus.Disconnected,
162
+ details,
163
+ });
164
+ const command = ideCommand(mockConfig);
165
+ const result = await command!.subCommands!.find(
166
+ (c) => c.name === 'status',
167
+ )!.action!(mockContext, '');
168
+ expect(mockGetConnectionStatus).toHaveBeenCalled();
169
+ expect(result).toEqual({
170
+ type: 'message',
171
+ messageType: 'error',
172
+ content: `🔴 Disconnected: ${details}`,
173
+ });
174
+ });
175
+ });
176
+
177
+ describe('install subcommand', () => {
178
+ const mockInstall = vi.fn();
179
+ beforeEach(() => {
180
+ vi.mocked(mockConfig.getIdeMode).mockReturnValue(true);
181
+ vi.mocked(mockConfig.getIdeClient).mockReturnValue({
182
+ getCurrentIde: () => DetectedIde.VSCode,
183
+ getConnectionStatus: () => ({
184
+ status: core.IDEConnectionStatus.Disconnected,
185
+ }),
186
+ getDetectedIdeDisplayName: () => 'VS Code',
187
+ } as unknown as ReturnType<Config['getIdeClient']>);
188
+ vi.mocked(core.getIdeInstaller).mockReturnValue({
189
+ install: mockInstall,
190
+ isInstalled: vi.fn(),
191
+ });
192
+ platformSpy.mockReturnValue('linux');
193
+ });
194
+
195
+ it('should install the extension', async () => {
196
+ mockInstall.mockResolvedValue({
197
+ success: true,
198
+ message: 'Successfully installed.',
199
+ });
200
+
201
+ const command = ideCommand(mockConfig);
202
+ await command!.subCommands!.find((c) => c.name === 'install')!.action!(
203
+ mockContext,
204
+ '',
205
+ );
206
+
207
+ expect(core.getIdeInstaller).toHaveBeenCalledWith('vscode');
208
+ expect(mockInstall).toHaveBeenCalled();
209
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
210
+ expect.objectContaining({
211
+ type: 'info',
212
+ text: `Installing IDE companion...`,
213
+ }),
214
+ expect.any(Number),
215
+ );
216
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
217
+ expect.objectContaining({
218
+ type: 'info',
219
+ text: 'Successfully installed.',
220
+ }),
221
+ expect.any(Number),
222
+ );
223
+ }, 10000);
224
+
225
+ it('should show an error if installation fails', async () => {
226
+ mockInstall.mockResolvedValue({
227
+ success: false,
228
+ message: 'Installation failed.',
229
+ });
230
+
231
+ const command = ideCommand(mockConfig);
232
+ await command!.subCommands!.find((c) => c.name === 'install')!.action!(
233
+ mockContext,
234
+ '',
235
+ );
236
+
237
+ expect(core.getIdeInstaller).toHaveBeenCalledWith('vscode');
238
+ expect(mockInstall).toHaveBeenCalled();
239
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
240
+ expect.objectContaining({
241
+ type: 'info',
242
+ text: `Installing IDE companion...`,
243
+ }),
244
+ expect.any(Number),
245
+ );
246
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
247
+ expect.objectContaining({
248
+ type: 'error',
249
+ text: 'Installation failed.',
250
+ }),
251
+ expect.any(Number),
252
+ );
253
+ });
254
+ });
255
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/ideCommand.ts ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ Config,
9
+ DetectedIde,
10
+ QWEN_CODE_COMPANION_EXTENSION_NAME,
11
+ IDEConnectionStatus,
12
+ getIdeInfo,
13
+ getIdeInstaller,
14
+ IdeClient,
15
+ type File,
16
+ ideContext,
17
+ } from '@qwen-code/qwen-code-core';
18
+ import path from 'node:path';
19
+ import {
20
+ CommandContext,
21
+ SlashCommand,
22
+ SlashCommandActionReturn,
23
+ CommandKind,
24
+ } from './types.js';
25
+ import { SettingScope } from '../../config/settings.js';
26
+
27
+ function getIdeStatusMessage(ideClient: IdeClient): {
28
+ messageType: 'info' | 'error';
29
+ content: string;
30
+ } {
31
+ const connection = ideClient.getConnectionStatus();
32
+ switch (connection.status) {
33
+ case IDEConnectionStatus.Connected:
34
+ return {
35
+ messageType: 'info',
36
+ content: `🟢 Connected to ${ideClient.getDetectedIdeDisplayName()}`,
37
+ };
38
+ case IDEConnectionStatus.Connecting:
39
+ return {
40
+ messageType: 'info',
41
+ content: `🟡 Connecting...`,
42
+ };
43
+ default: {
44
+ let content = `🔴 Disconnected`;
45
+ if (connection?.details) {
46
+ content += `: ${connection.details}`;
47
+ }
48
+ return {
49
+ messageType: 'error',
50
+ content,
51
+ };
52
+ }
53
+ }
54
+ }
55
+
56
+ function formatFileList(openFiles: File[]): string {
57
+ const basenameCounts = new Map<string, number>();
58
+ for (const file of openFiles) {
59
+ const basename = path.basename(file.path);
60
+ basenameCounts.set(basename, (basenameCounts.get(basename) || 0) + 1);
61
+ }
62
+
63
+ const fileList = openFiles
64
+ .map((file: File) => {
65
+ const basename = path.basename(file.path);
66
+ const isDuplicate = (basenameCounts.get(basename) || 0) > 1;
67
+ const parentDir = path.basename(path.dirname(file.path));
68
+ const displayName = isDuplicate
69
+ ? `${basename} (/${parentDir})`
70
+ : basename;
71
+
72
+ return ` - ${displayName}${file.isActive ? ' (active)' : ''}`;
73
+ })
74
+ .join('\n');
75
+
76
+ const infoMessage = `
77
+ (Note: The file list is limited to a number of recently accessed files within your workspace and only includes local files on disk)`;
78
+
79
+ return `\n\nOpen files:\n${fileList}\n${infoMessage}`;
80
+ }
81
+
82
+ async function getIdeStatusMessageWithFiles(ideClient: IdeClient): Promise<{
83
+ messageType: 'info' | 'error';
84
+ content: string;
85
+ }> {
86
+ const connection = ideClient.getConnectionStatus();
87
+ switch (connection.status) {
88
+ case IDEConnectionStatus.Connected: {
89
+ let content = `🟢 Connected to ${ideClient.getDetectedIdeDisplayName()}`;
90
+ const context = ideContext.getIdeContext();
91
+ const openFiles = context?.workspaceState?.openFiles;
92
+ if (openFiles && openFiles.length > 0) {
93
+ content += formatFileList(openFiles);
94
+ }
95
+ return {
96
+ messageType: 'info',
97
+ content,
98
+ };
99
+ }
100
+ case IDEConnectionStatus.Connecting:
101
+ return {
102
+ messageType: 'info',
103
+ content: `🟡 Connecting...`,
104
+ };
105
+ default: {
106
+ let content = `🔴 Disconnected`;
107
+ if (connection?.details) {
108
+ content += `: ${connection.details}`;
109
+ }
110
+ return {
111
+ messageType: 'error',
112
+ content,
113
+ };
114
+ }
115
+ }
116
+ }
117
+
118
+ export const ideCommand = (config: Config | null): SlashCommand | null => {
119
+ if (!config) {
120
+ return null;
121
+ }
122
+ const ideClient = config.getIdeClient();
123
+ const currentIDE = ideClient.getCurrentIde();
124
+ if (!currentIDE || !ideClient.getDetectedIdeDisplayName()) {
125
+ return {
126
+ name: 'ide',
127
+ description: 'manage IDE integration',
128
+ kind: CommandKind.BUILT_IN,
129
+ action: (): SlashCommandActionReturn =>
130
+ ({
131
+ type: 'message',
132
+ messageType: 'error',
133
+ content: `IDE integration is not supported in your current environment. To use this feature, run Qwen Code in one of these supported IDEs: ${Object.values(
134
+ DetectedIde,
135
+ )
136
+ .map((ide) => getIdeInfo(ide).displayName)
137
+ .join(', ')}`,
138
+ }) as const,
139
+ };
140
+ }
141
+
142
+ const ideSlashCommand: SlashCommand = {
143
+ name: 'ide',
144
+ description: 'manage IDE integration',
145
+ kind: CommandKind.BUILT_IN,
146
+ subCommands: [],
147
+ };
148
+
149
+ const statusCommand: SlashCommand = {
150
+ name: 'status',
151
+ description: 'check status of IDE integration',
152
+ kind: CommandKind.BUILT_IN,
153
+ action: async (): Promise<SlashCommandActionReturn> => {
154
+ const { messageType, content } =
155
+ await getIdeStatusMessageWithFiles(ideClient);
156
+ return {
157
+ type: 'message',
158
+ messageType,
159
+ content,
160
+ } as const;
161
+ },
162
+ };
163
+
164
+ const installCommand: SlashCommand = {
165
+ name: 'install',
166
+ description: `install required IDE companion for ${ideClient.getDetectedIdeDisplayName()}`,
167
+ kind: CommandKind.BUILT_IN,
168
+ action: async (context) => {
169
+ const installer = getIdeInstaller(currentIDE);
170
+ if (!installer) {
171
+ context.ui.addItem(
172
+ {
173
+ type: 'error',
174
+ text: `No installer is available for ${ideClient.getDetectedIdeDisplayName()}. Please install the '${QWEN_CODE_COMPANION_EXTENSION_NAME}' extension manually from the marketplace.`,
175
+ },
176
+ Date.now(),
177
+ );
178
+ return;
179
+ }
180
+
181
+ context.ui.addItem(
182
+ {
183
+ type: 'info',
184
+ text: `Installing IDE companion...`,
185
+ },
186
+ Date.now(),
187
+ );
188
+
189
+ const result = await installer.install();
190
+ context.ui.addItem(
191
+ {
192
+ type: result.success ? 'info' : 'error',
193
+ text: result.message,
194
+ },
195
+ Date.now(),
196
+ );
197
+ if (result.success) {
198
+ context.services.settings.setValue(SettingScope.User, 'ideMode', true);
199
+ // Poll for up to 5 seconds for the extension to activate.
200
+ for (let i = 0; i < 10; i++) {
201
+ await config.setIdeModeAndSyncConnection(true);
202
+ if (
203
+ ideClient.getConnectionStatus().status ===
204
+ IDEConnectionStatus.Connected
205
+ ) {
206
+ break;
207
+ }
208
+ await new Promise((resolve) => setTimeout(resolve, 500));
209
+ }
210
+
211
+ const { messageType, content } = getIdeStatusMessage(ideClient);
212
+ if (messageType === 'error') {
213
+ context.ui.addItem(
214
+ {
215
+ type: messageType,
216
+ text: `Failed to automatically enable IDE integration. To fix this, run the CLI in a new terminal window.`,
217
+ },
218
+ Date.now(),
219
+ );
220
+ } else {
221
+ context.ui.addItem(
222
+ {
223
+ type: messageType,
224
+ text: content,
225
+ },
226
+ Date.now(),
227
+ );
228
+ }
229
+ }
230
+ },
231
+ };
232
+
233
+ const enableCommand: SlashCommand = {
234
+ name: 'enable',
235
+ description: 'enable IDE integration',
236
+ kind: CommandKind.BUILT_IN,
237
+ action: async (context: CommandContext) => {
238
+ context.services.settings.setValue(SettingScope.User, 'ideMode', true);
239
+ await config.setIdeModeAndSyncConnection(true);
240
+ const { messageType, content } = getIdeStatusMessage(ideClient);
241
+ context.ui.addItem(
242
+ {
243
+ type: messageType,
244
+ text: content,
245
+ },
246
+ Date.now(),
247
+ );
248
+ },
249
+ };
250
+
251
+ const disableCommand: SlashCommand = {
252
+ name: 'disable',
253
+ description: 'disable IDE integration',
254
+ kind: CommandKind.BUILT_IN,
255
+ action: async (context: CommandContext) => {
256
+ context.services.settings.setValue(SettingScope.User, 'ideMode', false);
257
+ await config.setIdeModeAndSyncConnection(false);
258
+ const { messageType, content } = getIdeStatusMessage(ideClient);
259
+ context.ui.addItem(
260
+ {
261
+ type: messageType,
262
+ text: content,
263
+ },
264
+ Date.now(),
265
+ );
266
+ },
267
+ };
268
+
269
+ const { status } = ideClient.getConnectionStatus();
270
+ const isConnected = status === IDEConnectionStatus.Connected;
271
+
272
+ if (isConnected) {
273
+ ideSlashCommand.subCommands = [statusCommand, disableCommand];
274
+ } else {
275
+ ideSlashCommand.subCommands = [
276
+ enableCommand,
277
+ statusCommand,
278
+ installCommand,
279
+ ];
280
+ }
281
+
282
+ return ideSlashCommand;
283
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/initCommand.test.ts ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
10
+ import { initCommand } from './initCommand.js';
11
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
12
+ import { type CommandContext } from './types.js';
13
+
14
+ // Mock the 'fs' module with both named and default exports to avoid breaking default import sites
15
+ vi.mock('fs', async (importOriginal) => {
16
+ const actual = await importOriginal<typeof import('fs')>();
17
+ const existsSync = vi.fn();
18
+ const writeFileSync = vi.fn();
19
+ const readFileSync = vi.fn();
20
+ return {
21
+ ...actual,
22
+ existsSync,
23
+ writeFileSync,
24
+ readFileSync,
25
+ default: {
26
+ ...(actual as unknown as Record<string, unknown>),
27
+ existsSync,
28
+ writeFileSync,
29
+ readFileSync,
30
+ },
31
+ } as unknown as typeof import('fs');
32
+ });
33
+
34
+ describe('initCommand', () => {
35
+ let mockContext: CommandContext;
36
+ const targetDir = '/test/dir';
37
+ const DEFAULT_CONTEXT_FILENAME = 'QWEN.md';
38
+ const geminiMdPath = path.join(targetDir, DEFAULT_CONTEXT_FILENAME);
39
+
40
+ beforeEach(() => {
41
+ // Create a fresh mock context for each test
42
+ mockContext = createMockCommandContext({
43
+ services: {
44
+ config: {
45
+ getTargetDir: () => targetDir,
46
+ },
47
+ },
48
+ });
49
+ });
50
+
51
+ afterEach(() => {
52
+ // Clear all mocks after each test
53
+ vi.clearAllMocks();
54
+ });
55
+
56
+ it(`should inform the user if ${DEFAULT_CONTEXT_FILENAME} already exists and is non-empty`, async () => {
57
+ // Arrange: Simulate that the file exists
58
+ vi.mocked(fs.existsSync).mockReturnValue(true);
59
+ vi.spyOn(fs, 'readFileSync').mockReturnValue('# Existing content');
60
+
61
+ // Act: Run the command's action
62
+ const result = await initCommand.action!(mockContext, '');
63
+
64
+ // Assert: Check for the correct informational message
65
+ expect(result).toEqual({
66
+ type: 'message',
67
+ messageType: 'info',
68
+ content: `A ${DEFAULT_CONTEXT_FILENAME} file already exists in this directory. No changes were made.`,
69
+ });
70
+ // Assert: Ensure no file was written
71
+ expect(fs.writeFileSync).not.toHaveBeenCalled();
72
+ });
73
+
74
+ it(`should create ${DEFAULT_CONTEXT_FILENAME} and submit a prompt if it does not exist`, async () => {
75
+ // Arrange: Simulate that the file does not exist
76
+ vi.mocked(fs.existsSync).mockReturnValue(false);
77
+
78
+ // Act: Run the command's action
79
+ const result = await initCommand.action!(mockContext, '');
80
+
81
+ // Assert: Check that writeFileSync was called correctly
82
+ expect(fs.writeFileSync).toHaveBeenCalledWith(geminiMdPath, '', 'utf8');
83
+
84
+ // Assert: Check that an informational message was added to the UI
85
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
86
+ {
87
+ type: 'info',
88
+ text: `Empty ${DEFAULT_CONTEXT_FILENAME} created. Now analyzing the project to populate it.`,
89
+ },
90
+ expect.any(Number),
91
+ );
92
+
93
+ // Assert: Check that the correct prompt is submitted
94
+ expect(result.type).toBe('submit_prompt');
95
+ expect(result.content).toContain(
96
+ 'You are Qwen Code, an interactive CLI agent',
97
+ );
98
+ });
99
+
100
+ it(`should proceed to initialize when ${DEFAULT_CONTEXT_FILENAME} exists but is empty`, async () => {
101
+ vi.mocked(fs.existsSync).mockReturnValue(true);
102
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(' \n ');
103
+
104
+ const result = await initCommand.action!(mockContext, '');
105
+
106
+ expect(fs.writeFileSync).toHaveBeenCalledWith(geminiMdPath, '', 'utf8');
107
+ expect(result.type).toBe('submit_prompt');
108
+ });
109
+
110
+ it('should return an error if config is not available', async () => {
111
+ // Arrange: Create a context without config
112
+ const noConfigContext = createMockCommandContext();
113
+ if (noConfigContext.services) {
114
+ noConfigContext.services.config = null;
115
+ }
116
+
117
+ // Act: Run the command's action
118
+ const result = await initCommand.action!(noConfigContext, '');
119
+
120
+ // Assert: Check for the correct error message
121
+ expect(result).toEqual({
122
+ type: 'message',
123
+ messageType: 'error',
124
+ content: 'Configuration not available.',
125
+ });
126
+ });
127
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/initCommand.ts ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'fs';
8
+ import * as path from 'path';
9
+ import {
10
+ CommandContext,
11
+ SlashCommand,
12
+ SlashCommandActionReturn,
13
+ CommandKind,
14
+ } from './types.js';
15
+ import { getCurrentGeminiMdFilename } from '@qwen-code/qwen-code-core';
16
+
17
+ export const initCommand: SlashCommand = {
18
+ name: 'init',
19
+ description: 'Analyzes the project and creates a tailored QWEN.md file.',
20
+ kind: CommandKind.BUILT_IN,
21
+ action: async (
22
+ context: CommandContext,
23
+ _args: string,
24
+ ): Promise<SlashCommandActionReturn> => {
25
+ if (!context.services.config) {
26
+ return {
27
+ type: 'message',
28
+ messageType: 'error',
29
+ content: 'Configuration not available.',
30
+ };
31
+ }
32
+ const targetDir = context.services.config.getTargetDir();
33
+ const contextFileName = getCurrentGeminiMdFilename();
34
+ const contextFilePath = path.join(targetDir, contextFileName);
35
+
36
+ try {
37
+ if (fs.existsSync(contextFilePath)) {
38
+ // If file exists but is empty (or whitespace), continue to initialize; otherwise, bail out
39
+ try {
40
+ const existing = fs.readFileSync(contextFilePath, 'utf8');
41
+ if (existing && existing.trim().length > 0) {
42
+ return {
43
+ type: 'message',
44
+ messageType: 'info',
45
+ content: `A ${contextFileName} file already exists in this directory. No changes were made.`,
46
+ };
47
+ }
48
+ } catch {
49
+ // If we fail to read, conservatively proceed to (re)create the file
50
+ }
51
+ }
52
+
53
+ // Ensure an empty context file exists before prompting the model to populate it
54
+ try {
55
+ fs.writeFileSync(contextFilePath, '', 'utf8');
56
+ context.ui.addItem(
57
+ {
58
+ type: 'info',
59
+ text: `Empty ${contextFileName} created. Now analyzing the project to populate it.`,
60
+ },
61
+ Date.now(),
62
+ );
63
+ } catch (err) {
64
+ return {
65
+ type: 'message',
66
+ messageType: 'error',
67
+ content: `Failed to create ${contextFileName}: ${err instanceof Error ? err.message : String(err)}`,
68
+ };
69
+ }
70
+ } catch (error) {
71
+ return {
72
+ type: 'message',
73
+ messageType: 'error',
74
+ content: `Unexpected error preparing ${contextFileName}: ${error instanceof Error ? error.message : String(error)}`,
75
+ };
76
+ }
77
+
78
+ return {
79
+ type: 'submit_prompt',
80
+ content: `
81
+ You are Qwen Code, an interactive CLI agent. Analyze the current directory and generate a comprehensive ${contextFileName} file to be used as instructional context for future interactions.
82
+
83
+ **Analysis Process:**
84
+
85
+ 1. **Initial Exploration:**
86
+ * Start by listing the files and directories to get a high-level overview of the structure.
87
+ * Read the README file (e.g., \`README.md\`, \`README.txt\`) if it exists. This is often the best place to start.
88
+
89
+ 2. **Iterative Deep Dive (up to 10 files):**
90
+ * Based on your initial findings, select a few files that seem most important (e.g., configuration files, main source files, documentation).
91
+ * Read them. As you learn more, refine your understanding and decide which files to read next. You don't need to decide all 10 files at once. Let your discoveries guide your exploration.
92
+
93
+ 3. **Identify Project Type:**
94
+ * **Code Project:** Look for clues like \`package.json\`, \`requirements.txt\`, \`pom.xml\`, \`go.mod\`, \`Cargo.toml\`, \`build.gradle\`, or a \`src\` directory. If you find them, this is likely a software project.
95
+ * **Non-Code Project:** If you don't find code-related files, this might be a directory for documentation, research papers, notes, or something else.
96
+
97
+ **${contextFileName} Content Generation:**
98
+
99
+ **For a Code Project:**
100
+
101
+ * **Project Overview:** Write a clear and concise summary of the project's purpose, main technologies, and architecture.
102
+ * **Building and Running:** Document the key commands for building, running, and testing the project. Infer these from the files you've read (e.g., \`scripts\` in \`package.json\`, \`Makefile\`, etc.). If you can't find explicit commands, provide a placeholder with a TODO.
103
+ * **Development Conventions:** Describe any coding styles, testing practices, or contribution guidelines you can infer from the codebase.
104
+
105
+ **For a Non-Code Project:**
106
+
107
+ * **Directory Overview:** Describe the purpose and contents of the directory. What is it for? What kind of information does it hold?
108
+ * **Key Files:** List the most important files and briefly explain what they contain.
109
+ * **Usage:** Explain how the contents of this directory are intended to be used.
110
+
111
+ **Final Output:**
112
+
113
+ Write the complete content to the \`${contextFileName}\` file. The output must be well-formatted Markdown.
114
+ `,
115
+ };
116
+ },
117
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/mcpCommand.test.ts ADDED
@@ -0,0 +1,1057 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach } from 'vitest';
8
+ import { mcpCommand } from './mcpCommand.js';
9
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
10
+ import {
11
+ MCPServerStatus,
12
+ MCPDiscoveryState,
13
+ getMCPServerStatus,
14
+ getMCPDiscoveryState,
15
+ DiscoveredMCPTool,
16
+ } from '@qwen-code/qwen-code-core';
17
+
18
+ import { MessageActionReturn } from './types.js';
19
+ import { Type, CallableTool } from '@google/genai';
20
+
21
+ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
22
+ const actual =
23
+ await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
24
+ return {
25
+ ...actual,
26
+ getMCPServerStatus: vi.fn(),
27
+ getMCPDiscoveryState: vi.fn(),
28
+ MCPOAuthProvider: {
29
+ authenticate: vi.fn(),
30
+ },
31
+ MCPOAuthTokenStorage: {
32
+ getToken: vi.fn(),
33
+ isTokenExpired: vi.fn(),
34
+ },
35
+ };
36
+ });
37
+
38
+ // Helper function to check if result is a message action
39
+ const isMessageAction = (result: unknown): result is MessageActionReturn =>
40
+ result !== null &&
41
+ typeof result === 'object' &&
42
+ 'type' in result &&
43
+ result.type === 'message';
44
+
45
+ // Helper function to create a mock DiscoveredMCPTool
46
+ const createMockMCPTool = (
47
+ name: string,
48
+ serverName: string,
49
+ description?: string,
50
+ ) =>
51
+ new DiscoveredMCPTool(
52
+ {
53
+ callTool: vi.fn(),
54
+ tool: vi.fn(),
55
+ } as unknown as CallableTool,
56
+ serverName,
57
+ name,
58
+ description || `Description for ${name}`,
59
+ { type: Type.OBJECT, properties: {} },
60
+ name, // serverToolName same as name for simplicity
61
+ );
62
+
63
+ describe('mcpCommand', () => {
64
+ let mockContext: ReturnType<typeof createMockCommandContext>;
65
+ let mockConfig: {
66
+ getToolRegistry: ReturnType<typeof vi.fn>;
67
+ getMcpServers: ReturnType<typeof vi.fn>;
68
+ getBlockedMcpServers: ReturnType<typeof vi.fn>;
69
+ getPromptRegistry: ReturnType<typeof vi.fn>;
70
+ };
71
+
72
+ beforeEach(() => {
73
+ vi.clearAllMocks();
74
+
75
+ // Set up default mock environment
76
+ vi.unstubAllEnvs();
77
+
78
+ // Default mock implementations
79
+ vi.mocked(getMCPServerStatus).mockReturnValue(MCPServerStatus.CONNECTED);
80
+ vi.mocked(getMCPDiscoveryState).mockReturnValue(
81
+ MCPDiscoveryState.COMPLETED,
82
+ );
83
+
84
+ // Create mock config with all necessary methods
85
+ mockConfig = {
86
+ getToolRegistry: vi.fn().mockReturnValue({
87
+ getAllTools: vi.fn().mockReturnValue([]),
88
+ }),
89
+ getMcpServers: vi.fn().mockReturnValue({}),
90
+ getBlockedMcpServers: vi.fn().mockReturnValue([]),
91
+ getPromptRegistry: vi.fn().mockResolvedValue({
92
+ getAllPrompts: vi.fn().mockReturnValue([]),
93
+ getPromptsByServer: vi.fn().mockReturnValue([]),
94
+ }),
95
+ };
96
+
97
+ mockContext = createMockCommandContext({
98
+ services: {
99
+ config: mockConfig,
100
+ },
101
+ });
102
+ });
103
+
104
+ describe('basic functionality', () => {
105
+ it('should show an error if config is not available', async () => {
106
+ const contextWithoutConfig = createMockCommandContext({
107
+ services: {
108
+ config: null,
109
+ },
110
+ });
111
+
112
+ const result = await mcpCommand.action!(contextWithoutConfig, '');
113
+
114
+ expect(result).toEqual({
115
+ type: 'message',
116
+ messageType: 'error',
117
+ content: 'Config not loaded.',
118
+ });
119
+ });
120
+
121
+ it('should show an error if tool registry is not available', async () => {
122
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue(undefined);
123
+
124
+ const result = await mcpCommand.action!(mockContext, '');
125
+
126
+ expect(result).toEqual({
127
+ type: 'message',
128
+ messageType: 'error',
129
+ content: 'Could not retrieve tool registry.',
130
+ });
131
+ });
132
+ });
133
+
134
+ describe('no MCP servers configured', () => {
135
+ beforeEach(() => {
136
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
137
+ getAllTools: vi.fn().mockReturnValue([]),
138
+ });
139
+ mockConfig.getMcpServers = vi.fn().mockReturnValue({});
140
+ });
141
+
142
+ it('should display a message with a URL when no MCP servers are configured', async () => {
143
+ const result = await mcpCommand.action!(mockContext, '');
144
+
145
+ expect(result).toEqual({
146
+ type: 'message',
147
+ messageType: 'info',
148
+ content:
149
+ 'No MCP servers configured. Please view MCP documentation in your browser: https://qwenlm.github.io/qwen-code-docs/en/tools/mcp-server/#how-to-set-up-your-mcp-server or use the cli /docs command',
150
+ });
151
+ });
152
+ });
153
+
154
+ describe('with configured MCP servers', () => {
155
+ beforeEach(() => {
156
+ const mockMcpServers = {
157
+ server1: { command: 'cmd1' },
158
+ server2: { command: 'cmd2' },
159
+ server3: { command: 'cmd3' },
160
+ };
161
+
162
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
163
+ });
164
+
165
+ it('should display configured MCP servers with status indicators and their tools', async () => {
166
+ // Setup getMCPServerStatus mock implementation
167
+ vi.mocked(getMCPServerStatus).mockImplementation((serverName) => {
168
+ if (serverName === 'server1') return MCPServerStatus.CONNECTED;
169
+ if (serverName === 'server2') return MCPServerStatus.CONNECTED;
170
+ return MCPServerStatus.DISCONNECTED; // server3
171
+ });
172
+
173
+ // Mock tools from each server using actual DiscoveredMCPTool instances
174
+ const mockServer1Tools = [
175
+ createMockMCPTool('server1_tool1', 'server1'),
176
+ createMockMCPTool('server1_tool2', 'server1'),
177
+ ];
178
+ const mockServer2Tools = [createMockMCPTool('server2_tool1', 'server2')];
179
+ const mockServer3Tools = [createMockMCPTool('server3_tool1', 'server3')];
180
+
181
+ const allTools = [
182
+ ...mockServer1Tools,
183
+ ...mockServer2Tools,
184
+ ...mockServer3Tools,
185
+ ];
186
+
187
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
188
+ getAllTools: vi.fn().mockReturnValue(allTools),
189
+ });
190
+
191
+ const result = await mcpCommand.action!(mockContext, '');
192
+
193
+ expect(result).toEqual({
194
+ type: 'message',
195
+ messageType: 'info',
196
+ content: expect.stringContaining('Configured MCP servers:'),
197
+ });
198
+
199
+ expect(isMessageAction(result)).toBe(true);
200
+ if (isMessageAction(result)) {
201
+ const message = result.content;
202
+ // Server 1 - Connected
203
+ expect(message).toContain(
204
+ '🟢 \u001b[1mserver1\u001b[0m - Ready (2 tools)',
205
+ );
206
+ expect(message).toContain('server1_tool1');
207
+ expect(message).toContain('server1_tool2');
208
+
209
+ // Server 2 - Connected
210
+ expect(message).toContain(
211
+ '🟢 \u001b[1mserver2\u001b[0m - Ready (1 tool)',
212
+ );
213
+ expect(message).toContain('server2_tool1');
214
+
215
+ // Server 3 - Disconnected but with cached tools, so shows as Ready
216
+ expect(message).toContain(
217
+ '🟢 \u001b[1mserver3\u001b[0m - Ready (1 tool)',
218
+ );
219
+ expect(message).toContain('server3_tool1');
220
+
221
+ // Check that helpful tips are displayed when no arguments are provided
222
+ expect(message).toContain('💡 Tips:');
223
+ expect(message).toContain('/mcp desc');
224
+ expect(message).toContain('/mcp schema');
225
+ expect(message).toContain('/mcp nodesc');
226
+ expect(message).toContain('Ctrl+T');
227
+ }
228
+ });
229
+
230
+ it('should display tool descriptions when desc argument is used', async () => {
231
+ const mockMcpServers = {
232
+ server1: {
233
+ command: 'cmd1',
234
+ description: 'This is a server description',
235
+ },
236
+ };
237
+
238
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
239
+
240
+ // Mock tools with descriptions using actual DiscoveredMCPTool instances
241
+ const mockServerTools = [
242
+ createMockMCPTool('tool1', 'server1', 'This is tool 1 description'),
243
+ createMockMCPTool('tool2', 'server1', 'This is tool 2 description'),
244
+ ];
245
+
246
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
247
+ getAllTools: vi.fn().mockReturnValue(mockServerTools),
248
+ });
249
+
250
+ const result = await mcpCommand.action!(mockContext, 'desc');
251
+
252
+ expect(result).toEqual({
253
+ type: 'message',
254
+ messageType: 'info',
255
+ content: expect.stringContaining('Configured MCP servers:'),
256
+ });
257
+
258
+ expect(isMessageAction(result)).toBe(true);
259
+ if (isMessageAction(result)) {
260
+ const message = result.content;
261
+
262
+ // Check that server description is included
263
+ expect(message).toContain(
264
+ '\u001b[1mserver1\u001b[0m - Ready (2 tools)',
265
+ );
266
+ expect(message).toContain(
267
+ '\u001b[32mThis is a server description\u001b[0m',
268
+ );
269
+
270
+ // Check that tool descriptions are included
271
+ expect(message).toContain('\u001b[36mtool1\u001b[0m');
272
+ expect(message).toContain(
273
+ '\u001b[32mThis is tool 1 description\u001b[0m',
274
+ );
275
+ expect(message).toContain('\u001b[36mtool2\u001b[0m');
276
+ expect(message).toContain(
277
+ '\u001b[32mThis is tool 2 description\u001b[0m',
278
+ );
279
+
280
+ // Check that tips are NOT displayed when arguments are provided
281
+ expect(message).not.toContain('💡 Tips:');
282
+ }
283
+ });
284
+
285
+ it('should not display descriptions when nodesc argument is used', async () => {
286
+ const mockMcpServers = {
287
+ server1: {
288
+ command: 'cmd1',
289
+ description: 'This is a server description',
290
+ },
291
+ };
292
+
293
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
294
+
295
+ const mockServerTools = [
296
+ createMockMCPTool('tool1', 'server1', 'This is tool 1 description'),
297
+ ];
298
+
299
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
300
+ getAllTools: vi.fn().mockReturnValue(mockServerTools),
301
+ });
302
+
303
+ const result = await mcpCommand.action!(mockContext, 'nodesc');
304
+
305
+ expect(result).toEqual({
306
+ type: 'message',
307
+ messageType: 'info',
308
+ content: expect.stringContaining('Configured MCP servers:'),
309
+ });
310
+
311
+ expect(isMessageAction(result)).toBe(true);
312
+ if (isMessageAction(result)) {
313
+ const message = result.content;
314
+
315
+ // Check that descriptions are not included
316
+ expect(message).not.toContain('This is a server description');
317
+ expect(message).not.toContain('This is tool 1 description');
318
+ expect(message).toContain('\u001b[36mtool1\u001b[0m');
319
+
320
+ // Check that tips are NOT displayed when arguments are provided
321
+ expect(message).not.toContain('💡 Tips:');
322
+ }
323
+ });
324
+
325
+ it('should indicate when a server has no tools', async () => {
326
+ const mockMcpServers = {
327
+ server1: { command: 'cmd1' },
328
+ server2: { command: 'cmd2' },
329
+ };
330
+
331
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
332
+
333
+ // Setup server statuses
334
+ vi.mocked(getMCPServerStatus).mockImplementation((serverName) => {
335
+ if (serverName === 'server1') return MCPServerStatus.CONNECTED;
336
+ if (serverName === 'server2') return MCPServerStatus.DISCONNECTED;
337
+ return MCPServerStatus.DISCONNECTED;
338
+ });
339
+
340
+ // Mock tools - only server1 has tools
341
+ const mockServerTools = [createMockMCPTool('server1_tool1', 'server1')];
342
+
343
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
344
+ getAllTools: vi.fn().mockReturnValue(mockServerTools),
345
+ });
346
+
347
+ const result = await mcpCommand.action!(mockContext, '');
348
+
349
+ expect(isMessageAction(result)).toBe(true);
350
+ if (isMessageAction(result)) {
351
+ const message = result.content;
352
+ expect(message).toContain(
353
+ '🟢 \u001b[1mserver1\u001b[0m - Ready (1 tool)',
354
+ );
355
+ expect(message).toContain('\u001b[36mserver1_tool1\u001b[0m');
356
+ expect(message).toContain(
357
+ '🔴 \u001b[1mserver2\u001b[0m - Disconnected (0 tools cached)',
358
+ );
359
+ expect(message).toContain('No tools or prompts available');
360
+ }
361
+ });
362
+
363
+ it('should show startup indicator when servers are connecting', async () => {
364
+ const mockMcpServers = {
365
+ server1: { command: 'cmd1' },
366
+ server2: { command: 'cmd2' },
367
+ };
368
+
369
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
370
+
371
+ // Setup server statuses with one connecting
372
+ vi.mocked(getMCPServerStatus).mockImplementation((serverName) => {
373
+ if (serverName === 'server1') return MCPServerStatus.CONNECTED;
374
+ if (serverName === 'server2') return MCPServerStatus.CONNECTING;
375
+ return MCPServerStatus.DISCONNECTED;
376
+ });
377
+
378
+ // Setup discovery state as in progress
379
+ vi.mocked(getMCPDiscoveryState).mockReturnValue(
380
+ MCPDiscoveryState.IN_PROGRESS,
381
+ );
382
+
383
+ // Mock tools
384
+ const mockServerTools = [
385
+ createMockMCPTool('server1_tool1', 'server1'),
386
+ createMockMCPTool('server2_tool1', 'server2'),
387
+ ];
388
+
389
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
390
+ getAllTools: vi.fn().mockReturnValue(mockServerTools),
391
+ });
392
+
393
+ const result = await mcpCommand.action!(mockContext, '');
394
+
395
+ expect(isMessageAction(result)).toBe(true);
396
+ if (isMessageAction(result)) {
397
+ const message = result.content;
398
+
399
+ // Check that startup indicator is shown
400
+ expect(message).toContain(
401
+ '⏳ MCP servers are starting up (1 initializing)...',
402
+ );
403
+ expect(message).toContain(
404
+ 'Note: First startup may take longer. Tool availability will update automatically.',
405
+ );
406
+
407
+ // Check server statuses
408
+ expect(message).toContain(
409
+ '🟢 \u001b[1mserver1\u001b[0m - Ready (1 tool)',
410
+ );
411
+ expect(message).toContain(
412
+ '🔄 \u001b[1mserver2\u001b[0m - Starting... (first startup may take longer) (tools and prompts will appear when ready)',
413
+ );
414
+ }
415
+ });
416
+
417
+ it('should display the extension name for servers from extensions', async () => {
418
+ const mockMcpServers = {
419
+ server1: { command: 'cmd1', extensionName: 'my-extension' },
420
+ };
421
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
422
+
423
+ const result = await mcpCommand.action!(mockContext, '');
424
+
425
+ expect(isMessageAction(result)).toBe(true);
426
+ if (isMessageAction(result)) {
427
+ const message = result.content;
428
+ expect(message).toContain('server1 (from my-extension)');
429
+ }
430
+ });
431
+
432
+ it('should display blocked MCP servers', async () => {
433
+ mockConfig.getMcpServers = vi.fn().mockReturnValue({});
434
+ const blockedServers = [
435
+ { name: 'blocked-server', extensionName: 'my-extension' },
436
+ ];
437
+ mockConfig.getBlockedMcpServers = vi.fn().mockReturnValue(blockedServers);
438
+
439
+ const result = await mcpCommand.action!(mockContext, '');
440
+
441
+ expect(isMessageAction(result)).toBe(true);
442
+ if (isMessageAction(result)) {
443
+ const message = result.content;
444
+ expect(message).toContain(
445
+ '🔴 \u001b[1mblocked-server (from my-extension)\u001b[0m - Blocked',
446
+ );
447
+ }
448
+ });
449
+
450
+ it('should display both active and blocked servers correctly', async () => {
451
+ const mockMcpServers = {
452
+ server1: { command: 'cmd1', extensionName: 'my-extension' },
453
+ };
454
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
455
+ const blockedServers = [
456
+ { name: 'blocked-server', extensionName: 'another-extension' },
457
+ ];
458
+ mockConfig.getBlockedMcpServers = vi.fn().mockReturnValue(blockedServers);
459
+
460
+ const result = await mcpCommand.action!(mockContext, '');
461
+
462
+ expect(isMessageAction(result)).toBe(true);
463
+ if (isMessageAction(result)) {
464
+ const message = result.content;
465
+ expect(message).toContain('server1 (from my-extension)');
466
+ expect(message).toContain(
467
+ '🔴 \u001b[1mblocked-server (from another-extension)\u001b[0m - Blocked',
468
+ );
469
+ }
470
+ });
471
+ });
472
+
473
+ describe('schema functionality', () => {
474
+ it('should display tool schemas when schema argument is used', async () => {
475
+ const mockMcpServers = {
476
+ server1: {
477
+ command: 'cmd1',
478
+ description: 'This is a server description',
479
+ },
480
+ };
481
+
482
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
483
+
484
+ // Create tools with parameter schemas
485
+ const mockCallableTool1: CallableTool = {
486
+ callTool: vi.fn(),
487
+ tool: vi.fn(),
488
+ } as unknown as CallableTool;
489
+ const mockCallableTool2: CallableTool = {
490
+ callTool: vi.fn(),
491
+ tool: vi.fn(),
492
+ } as unknown as CallableTool;
493
+
494
+ const tool1 = new DiscoveredMCPTool(
495
+ mockCallableTool1,
496
+ 'server1',
497
+ 'tool1',
498
+ 'This is tool 1 description',
499
+ {
500
+ type: Type.OBJECT,
501
+ properties: {
502
+ param1: { type: Type.STRING, description: 'First parameter' },
503
+ },
504
+ required: ['param1'],
505
+ },
506
+ 'tool1',
507
+ );
508
+
509
+ const tool2 = new DiscoveredMCPTool(
510
+ mockCallableTool2,
511
+ 'server1',
512
+ 'tool2',
513
+ 'This is tool 2 description',
514
+ {
515
+ type: Type.OBJECT,
516
+ properties: {
517
+ param2: { type: Type.NUMBER, description: 'Second parameter' },
518
+ },
519
+ required: ['param2'],
520
+ },
521
+ 'tool2',
522
+ );
523
+
524
+ const mockServerTools = [tool1, tool2];
525
+
526
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
527
+ getAllTools: vi.fn().mockReturnValue(mockServerTools),
528
+ });
529
+
530
+ const result = await mcpCommand.action!(mockContext, 'schema');
531
+
532
+ expect(result).toEqual({
533
+ type: 'message',
534
+ messageType: 'info',
535
+ content: expect.stringContaining('Configured MCP servers:'),
536
+ });
537
+
538
+ expect(isMessageAction(result)).toBe(true);
539
+ if (isMessageAction(result)) {
540
+ const message = result.content;
541
+
542
+ // Check that server description is included
543
+ expect(message).toContain('Ready (2 tools)');
544
+ expect(message).toContain('This is a server description');
545
+
546
+ // Check that tool descriptions and schemas are included
547
+ expect(message).toContain('This is tool 1 description');
548
+ expect(message).toContain('Parameters:');
549
+ expect(message).toContain('param1');
550
+ expect(message).toContain('STRING');
551
+ expect(message).toContain('This is tool 2 description');
552
+ expect(message).toContain('param2');
553
+ expect(message).toContain('NUMBER');
554
+ }
555
+ });
556
+
557
+ it('should handle tools without parameter schemas gracefully', async () => {
558
+ const mockMcpServers = {
559
+ server1: { command: 'cmd1' },
560
+ };
561
+
562
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
563
+
564
+ // Mock tools without parameter schemas
565
+ const mockServerTools = [
566
+ createMockMCPTool('tool1', 'server1', 'Tool without schema'),
567
+ ];
568
+
569
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
570
+ getAllTools: vi.fn().mockReturnValue(mockServerTools),
571
+ });
572
+
573
+ const result = await mcpCommand.action!(mockContext, 'schema');
574
+
575
+ expect(result).toEqual({
576
+ type: 'message',
577
+ messageType: 'info',
578
+ content: expect.stringContaining('Configured MCP servers:'),
579
+ });
580
+
581
+ expect(isMessageAction(result)).toBe(true);
582
+ if (isMessageAction(result)) {
583
+ const message = result.content;
584
+ expect(message).toContain('tool1');
585
+ expect(message).toContain('Tool without schema');
586
+ // Should not crash when parameterSchema is undefined
587
+ }
588
+ });
589
+ });
590
+
591
+ describe('argument parsing', () => {
592
+ beforeEach(() => {
593
+ const mockMcpServers = {
594
+ server1: {
595
+ command: 'cmd1',
596
+ description: 'Server description',
597
+ },
598
+ };
599
+
600
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
601
+
602
+ const mockServerTools = [
603
+ createMockMCPTool('tool1', 'server1', 'Test tool'),
604
+ ];
605
+
606
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
607
+ getAllTools: vi.fn().mockReturnValue(mockServerTools),
608
+ });
609
+ });
610
+
611
+ it('should handle "descriptions" as alias for "desc"', async () => {
612
+ const result = await mcpCommand.action!(mockContext, 'descriptions');
613
+
614
+ expect(isMessageAction(result)).toBe(true);
615
+ if (isMessageAction(result)) {
616
+ const message = result.content;
617
+ expect(message).toContain('Test tool');
618
+ expect(message).toContain('Server description');
619
+ }
620
+ });
621
+
622
+ it('should handle "nodescriptions" as alias for "nodesc"', async () => {
623
+ const result = await mcpCommand.action!(mockContext, 'nodescriptions');
624
+
625
+ expect(isMessageAction(result)).toBe(true);
626
+ if (isMessageAction(result)) {
627
+ const message = result.content;
628
+ expect(message).not.toContain('Test tool');
629
+ expect(message).not.toContain('Server description');
630
+ expect(message).toContain('\u001b[36mtool1\u001b[0m');
631
+ }
632
+ });
633
+
634
+ it('should handle mixed case arguments', async () => {
635
+ const result = await mcpCommand.action!(mockContext, 'DESC');
636
+
637
+ expect(isMessageAction(result)).toBe(true);
638
+ if (isMessageAction(result)) {
639
+ const message = result.content;
640
+ expect(message).toContain('Test tool');
641
+ expect(message).toContain('Server description');
642
+ }
643
+ });
644
+
645
+ it('should handle multiple arguments - "schema desc"', async () => {
646
+ const result = await mcpCommand.action!(mockContext, 'schema desc');
647
+
648
+ expect(isMessageAction(result)).toBe(true);
649
+ if (isMessageAction(result)) {
650
+ const message = result.content;
651
+ expect(message).toContain('Test tool');
652
+ expect(message).toContain('Server description');
653
+ expect(message).toContain('Parameters:');
654
+ }
655
+ });
656
+
657
+ it('should handle multiple arguments - "desc schema"', async () => {
658
+ const result = await mcpCommand.action!(mockContext, 'desc schema');
659
+
660
+ expect(isMessageAction(result)).toBe(true);
661
+ if (isMessageAction(result)) {
662
+ const message = result.content;
663
+ expect(message).toContain('Test tool');
664
+ expect(message).toContain('Server description');
665
+ expect(message).toContain('Parameters:');
666
+ }
667
+ });
668
+
669
+ it('should handle "schema" alone showing descriptions', async () => {
670
+ const result = await mcpCommand.action!(mockContext, 'schema');
671
+
672
+ expect(isMessageAction(result)).toBe(true);
673
+ if (isMessageAction(result)) {
674
+ const message = result.content;
675
+ expect(message).toContain('Test tool');
676
+ expect(message).toContain('Server description');
677
+ expect(message).toContain('Parameters:');
678
+ }
679
+ });
680
+
681
+ it('should handle "nodesc" overriding "schema" - "schema nodesc"', async () => {
682
+ const result = await mcpCommand.action!(mockContext, 'schema nodesc');
683
+
684
+ expect(isMessageAction(result)).toBe(true);
685
+ if (isMessageAction(result)) {
686
+ const message = result.content;
687
+ expect(message).not.toContain('Test tool');
688
+ expect(message).not.toContain('Server description');
689
+ expect(message).toContain('Parameters:'); // Schema should still show
690
+ expect(message).toContain('\u001b[36mtool1\u001b[0m');
691
+ }
692
+ });
693
+
694
+ it('should handle "nodesc" overriding "desc" - "desc nodesc"', async () => {
695
+ const result = await mcpCommand.action!(mockContext, 'desc nodesc');
696
+
697
+ expect(isMessageAction(result)).toBe(true);
698
+ if (isMessageAction(result)) {
699
+ const message = result.content;
700
+ expect(message).not.toContain('Test tool');
701
+ expect(message).not.toContain('Server description');
702
+ expect(message).not.toContain('Parameters:');
703
+ expect(message).toContain('\u001b[36mtool1\u001b[0m');
704
+ }
705
+ });
706
+
707
+ it('should handle "nodesc" overriding both "desc" and "schema" - "desc schema nodesc"', async () => {
708
+ const result = await mcpCommand.action!(
709
+ mockContext,
710
+ 'desc schema nodesc',
711
+ );
712
+
713
+ expect(isMessageAction(result)).toBe(true);
714
+ if (isMessageAction(result)) {
715
+ const message = result.content;
716
+ expect(message).not.toContain('Test tool');
717
+ expect(message).not.toContain('Server description');
718
+ expect(message).toContain('Parameters:'); // Schema should still show
719
+ expect(message).toContain('\u001b[36mtool1\u001b[0m');
720
+ }
721
+ });
722
+
723
+ it('should handle extra whitespace in arguments', async () => {
724
+ const result = await mcpCommand.action!(mockContext, ' desc schema ');
725
+
726
+ expect(isMessageAction(result)).toBe(true);
727
+ if (isMessageAction(result)) {
728
+ const message = result.content;
729
+ expect(message).toContain('Test tool');
730
+ expect(message).toContain('Server description');
731
+ expect(message).toContain('Parameters:');
732
+ }
733
+ });
734
+
735
+ it('should handle empty arguments gracefully', async () => {
736
+ const result = await mcpCommand.action!(mockContext, '');
737
+
738
+ expect(isMessageAction(result)).toBe(true);
739
+ if (isMessageAction(result)) {
740
+ const message = result.content;
741
+ expect(message).not.toContain('Test tool');
742
+ expect(message).not.toContain('Server description');
743
+ expect(message).not.toContain('Parameters:');
744
+ expect(message).toContain('\u001b[36mtool1\u001b[0m');
745
+ }
746
+ });
747
+
748
+ it('should handle unknown arguments gracefully', async () => {
749
+ const result = await mcpCommand.action!(mockContext, 'unknown arg');
750
+
751
+ expect(isMessageAction(result)).toBe(true);
752
+ if (isMessageAction(result)) {
753
+ const message = result.content;
754
+ expect(message).not.toContain('Test tool');
755
+ expect(message).not.toContain('Server description');
756
+ expect(message).not.toContain('Parameters:');
757
+ expect(message).toContain('\u001b[36mtool1\u001b[0m');
758
+ }
759
+ });
760
+ });
761
+
762
+ describe('edge cases', () => {
763
+ it('should handle empty server names gracefully', async () => {
764
+ const mockMcpServers = {
765
+ '': { command: 'cmd1' }, // Empty server name
766
+ };
767
+
768
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
769
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
770
+ getAllTools: vi.fn().mockReturnValue([]),
771
+ });
772
+
773
+ const result = await mcpCommand.action!(mockContext, '');
774
+
775
+ expect(result).toEqual({
776
+ type: 'message',
777
+ messageType: 'info',
778
+ content: expect.stringContaining('Configured MCP servers:'),
779
+ });
780
+ });
781
+
782
+ it('should handle servers with special characters in names', async () => {
783
+ const mockMcpServers = {
784
+ 'server-with-dashes': { command: 'cmd1' },
785
+ server_with_underscores: { command: 'cmd2' },
786
+ 'server.with.dots': { command: 'cmd3' },
787
+ };
788
+
789
+ mockConfig.getMcpServers = vi.fn().mockReturnValue(mockMcpServers);
790
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue({
791
+ getAllTools: vi.fn().mockReturnValue([]),
792
+ });
793
+
794
+ const result = await mcpCommand.action!(mockContext, '');
795
+
796
+ expect(isMessageAction(result)).toBe(true);
797
+ if (isMessageAction(result)) {
798
+ const message = result.content;
799
+ expect(message).toContain('server-with-dashes');
800
+ expect(message).toContain('server_with_underscores');
801
+ expect(message).toContain('server.with.dots');
802
+ }
803
+ });
804
+ });
805
+
806
+ describe('auth subcommand', () => {
807
+ beforeEach(() => {
808
+ vi.clearAllMocks();
809
+ });
810
+
811
+ it('should list OAuth-enabled servers when no server name is provided', async () => {
812
+ const context = createMockCommandContext({
813
+ services: {
814
+ config: {
815
+ getMcpServers: vi.fn().mockReturnValue({
816
+ 'oauth-server': { oauth: { enabled: true } },
817
+ 'regular-server': {},
818
+ 'another-oauth': { oauth: { enabled: true } },
819
+ }),
820
+ },
821
+ },
822
+ });
823
+
824
+ const authCommand = mcpCommand.subCommands?.find(
825
+ (cmd) => cmd.name === 'auth',
826
+ );
827
+ expect(authCommand).toBeDefined();
828
+
829
+ const result = await authCommand!.action!(context, '');
830
+ expect(isMessageAction(result)).toBe(true);
831
+ if (isMessageAction(result)) {
832
+ expect(result.messageType).toBe('info');
833
+ expect(result.content).toContain('oauth-server');
834
+ expect(result.content).toContain('another-oauth');
835
+ expect(result.content).not.toContain('regular-server');
836
+ expect(result.content).toContain('/mcp auth <server-name>');
837
+ }
838
+ });
839
+
840
+ it('should show message when no OAuth servers are configured', async () => {
841
+ const context = createMockCommandContext({
842
+ services: {
843
+ config: {
844
+ getMcpServers: vi.fn().mockReturnValue({
845
+ 'regular-server': {},
846
+ }),
847
+ },
848
+ },
849
+ });
850
+
851
+ const authCommand = mcpCommand.subCommands?.find(
852
+ (cmd) => cmd.name === 'auth',
853
+ );
854
+ const result = await authCommand!.action!(context, '');
855
+
856
+ expect(isMessageAction(result)).toBe(true);
857
+ if (isMessageAction(result)) {
858
+ expect(result.messageType).toBe('info');
859
+ expect(result.content).toBe(
860
+ 'No MCP servers configured with OAuth authentication.',
861
+ );
862
+ }
863
+ });
864
+
865
+ it('should authenticate with a specific server', async () => {
866
+ const mockToolRegistry = {
867
+ discoverToolsForServer: vi.fn(),
868
+ };
869
+ const mockGeminiClient = {
870
+ setTools: vi.fn(),
871
+ };
872
+
873
+ const context = createMockCommandContext({
874
+ services: {
875
+ config: {
876
+ getMcpServers: vi.fn().mockReturnValue({
877
+ 'test-server': {
878
+ url: 'http://localhost:3000',
879
+ oauth: { enabled: true },
880
+ },
881
+ }),
882
+ getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
883
+ getGeminiClient: vi.fn().mockReturnValue(mockGeminiClient),
884
+ getPromptRegistry: vi.fn().mockResolvedValue({
885
+ removePromptsByServer: vi.fn(),
886
+ }),
887
+ },
888
+ },
889
+ });
890
+ // Mock the reloadCommands function
891
+ context.ui.reloadCommands = vi.fn();
892
+
893
+ const { MCPOAuthProvider } = await import('@qwen-code/qwen-code-core');
894
+
895
+ const authCommand = mcpCommand.subCommands?.find(
896
+ (cmd) => cmd.name === 'auth',
897
+ );
898
+ const result = await authCommand!.action!(context, 'test-server');
899
+
900
+ expect(MCPOAuthProvider.authenticate).toHaveBeenCalledWith(
901
+ 'test-server',
902
+ { enabled: true },
903
+ 'http://localhost:3000',
904
+ );
905
+ expect(mockToolRegistry.discoverToolsForServer).toHaveBeenCalledWith(
906
+ 'test-server',
907
+ );
908
+ expect(mockGeminiClient.setTools).toHaveBeenCalled();
909
+ expect(context.ui.reloadCommands).toHaveBeenCalledTimes(1);
910
+
911
+ expect(isMessageAction(result)).toBe(true);
912
+ if (isMessageAction(result)) {
913
+ expect(result.messageType).toBe('info');
914
+ expect(result.content).toContain('Successfully authenticated');
915
+ }
916
+ });
917
+
918
+ it('should handle authentication errors', async () => {
919
+ const context = createMockCommandContext({
920
+ services: {
921
+ config: {
922
+ getMcpServers: vi.fn().mockReturnValue({
923
+ 'test-server': { oauth: { enabled: true } },
924
+ }),
925
+ },
926
+ },
927
+ });
928
+
929
+ const { MCPOAuthProvider } = await import('@qwen-code/qwen-code-core');
930
+ (
931
+ MCPOAuthProvider.authenticate as ReturnType<typeof vi.fn>
932
+ ).mockRejectedValue(new Error('Auth failed'));
933
+
934
+ const authCommand = mcpCommand.subCommands?.find(
935
+ (cmd) => cmd.name === 'auth',
936
+ );
937
+ const result = await authCommand!.action!(context, 'test-server');
938
+
939
+ expect(isMessageAction(result)).toBe(true);
940
+ if (isMessageAction(result)) {
941
+ expect(result.messageType).toBe('error');
942
+ expect(result.content).toContain('Failed to authenticate');
943
+ expect(result.content).toContain('Auth failed');
944
+ }
945
+ });
946
+
947
+ it('should handle non-existent server', async () => {
948
+ const context = createMockCommandContext({
949
+ services: {
950
+ config: {
951
+ getMcpServers: vi.fn().mockReturnValue({
952
+ 'existing-server': {},
953
+ }),
954
+ },
955
+ },
956
+ });
957
+
958
+ const authCommand = mcpCommand.subCommands?.find(
959
+ (cmd) => cmd.name === 'auth',
960
+ );
961
+ const result = await authCommand!.action!(context, 'non-existent');
962
+
963
+ expect(isMessageAction(result)).toBe(true);
964
+ if (isMessageAction(result)) {
965
+ expect(result.messageType).toBe('error');
966
+ expect(result.content).toContain("MCP server 'non-existent' not found");
967
+ }
968
+ });
969
+ });
970
+
971
+ describe('refresh subcommand', () => {
972
+ it('should refresh the list of tools and display the status', async () => {
973
+ const mockToolRegistry = {
974
+ discoverMcpTools: vi.fn(),
975
+ restartMcpServers: vi.fn(),
976
+ getAllTools: vi.fn().mockReturnValue([]),
977
+ };
978
+ const mockGeminiClient = {
979
+ setTools: vi.fn(),
980
+ };
981
+
982
+ const context = createMockCommandContext({
983
+ services: {
984
+ config: {
985
+ getMcpServers: vi.fn().mockReturnValue({ server1: {} }),
986
+ getBlockedMcpServers: vi.fn().mockReturnValue([]),
987
+ getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
988
+ getGeminiClient: vi.fn().mockReturnValue(mockGeminiClient),
989
+ getPromptRegistry: vi.fn().mockResolvedValue({
990
+ getPromptsByServer: vi.fn().mockReturnValue([]),
991
+ }),
992
+ },
993
+ },
994
+ });
995
+ // Mock the reloadCommands function, which is new logic.
996
+ context.ui.reloadCommands = vi.fn();
997
+
998
+ const refreshCommand = mcpCommand.subCommands?.find(
999
+ (cmd) => cmd.name === 'refresh',
1000
+ );
1001
+ expect(refreshCommand).toBeDefined();
1002
+
1003
+ const result = await refreshCommand!.action!(context, '');
1004
+
1005
+ expect(context.ui.addItem).toHaveBeenCalledWith(
1006
+ {
1007
+ type: 'info',
1008
+ text: 'Restarting MCP servers...',
1009
+ },
1010
+ expect.any(Number),
1011
+ );
1012
+ expect(mockToolRegistry.restartMcpServers).toHaveBeenCalled();
1013
+ expect(mockGeminiClient.setTools).toHaveBeenCalled();
1014
+ expect(context.ui.reloadCommands).toHaveBeenCalledTimes(1);
1015
+
1016
+ expect(isMessageAction(result)).toBe(true);
1017
+ if (isMessageAction(result)) {
1018
+ expect(result.messageType).toBe('info');
1019
+ expect(result.content).toContain('Configured MCP servers:');
1020
+ }
1021
+ });
1022
+
1023
+ it('should show an error if config is not available', async () => {
1024
+ const contextWithoutConfig = createMockCommandContext({
1025
+ services: {
1026
+ config: null,
1027
+ },
1028
+ });
1029
+
1030
+ const refreshCommand = mcpCommand.subCommands?.find(
1031
+ (cmd) => cmd.name === 'refresh',
1032
+ );
1033
+ const result = await refreshCommand!.action!(contextWithoutConfig, '');
1034
+
1035
+ expect(result).toEqual({
1036
+ type: 'message',
1037
+ messageType: 'error',
1038
+ content: 'Config not loaded.',
1039
+ });
1040
+ });
1041
+
1042
+ it('should show an error if tool registry is not available', async () => {
1043
+ mockConfig.getToolRegistry = vi.fn().mockReturnValue(undefined);
1044
+
1045
+ const refreshCommand = mcpCommand.subCommands?.find(
1046
+ (cmd) => cmd.name === 'refresh',
1047
+ );
1048
+ const result = await refreshCommand!.action!(mockContext, '');
1049
+
1050
+ expect(result).toEqual({
1051
+ type: 'message',
1052
+ messageType: 'error',
1053
+ content: 'Could not retrieve tool registry.',
1054
+ });
1055
+ });
1056
+ });
1057
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/mcpCommand.ts ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ SlashCommand,
9
+ SlashCommandActionReturn,
10
+ CommandContext,
11
+ CommandKind,
12
+ MessageActionReturn,
13
+ } from './types.js';
14
+ import {
15
+ DiscoveredMCPPrompt,
16
+ DiscoveredMCPTool,
17
+ getMCPDiscoveryState,
18
+ getMCPServerStatus,
19
+ MCPDiscoveryState,
20
+ MCPServerStatus,
21
+ mcpServerRequiresOAuth,
22
+ getErrorMessage,
23
+ } from '@qwen-code/qwen-code-core';
24
+
25
+ const COLOR_GREEN = '\u001b[32m';
26
+ const COLOR_YELLOW = '\u001b[33m';
27
+ const COLOR_RED = '\u001b[31m';
28
+ const COLOR_CYAN = '\u001b[36m';
29
+ const COLOR_GREY = '\u001b[90m';
30
+ const RESET_COLOR = '\u001b[0m';
31
+
32
+ const getMcpStatus = async (
33
+ context: CommandContext,
34
+ showDescriptions: boolean,
35
+ showSchema: boolean,
36
+ showTips: boolean = false,
37
+ ): Promise<SlashCommandActionReturn> => {
38
+ const { config } = context.services;
39
+ if (!config) {
40
+ return {
41
+ type: 'message',
42
+ messageType: 'error',
43
+ content: 'Config not loaded.',
44
+ };
45
+ }
46
+
47
+ const toolRegistry = config.getToolRegistry();
48
+ if (!toolRegistry) {
49
+ return {
50
+ type: 'message',
51
+ messageType: 'error',
52
+ content: 'Could not retrieve tool registry.',
53
+ };
54
+ }
55
+
56
+ const mcpServers = config.getMcpServers() || {};
57
+ const serverNames = Object.keys(mcpServers);
58
+ const blockedMcpServers = config.getBlockedMcpServers() || [];
59
+
60
+ if (serverNames.length === 0 && blockedMcpServers.length === 0) {
61
+ const docsUrl =
62
+ 'https://qwenlm.github.io/qwen-code-docs/en/tools/mcp-server/#how-to-set-up-your-mcp-server';
63
+ return {
64
+ type: 'message',
65
+ messageType: 'info',
66
+ content: `No MCP servers configured. Please view MCP documentation in your browser: ${docsUrl} or use the cli /docs command`,
67
+ };
68
+ }
69
+
70
+ // Check if any servers are still connecting
71
+ const connectingServers = serverNames.filter(
72
+ (name) => getMCPServerStatus(name) === MCPServerStatus.CONNECTING,
73
+ );
74
+ const discoveryState = getMCPDiscoveryState();
75
+
76
+ let message = '';
77
+
78
+ // Add overall discovery status message if needed
79
+ if (
80
+ discoveryState === MCPDiscoveryState.IN_PROGRESS ||
81
+ connectingServers.length > 0
82
+ ) {
83
+ message += `${COLOR_YELLOW}⏳ MCP servers are starting up (${connectingServers.length} initializing)...${RESET_COLOR}\n`;
84
+ message += `${COLOR_CYAN}Note: First startup may take longer. Tool availability will update automatically.${RESET_COLOR}\n\n`;
85
+ }
86
+
87
+ message += 'Configured MCP servers:\n\n';
88
+
89
+ const allTools = toolRegistry.getAllTools();
90
+ for (const serverName of serverNames) {
91
+ const serverTools = allTools.filter(
92
+ (tool) =>
93
+ tool instanceof DiscoveredMCPTool && tool.serverName === serverName,
94
+ ) as DiscoveredMCPTool[];
95
+ const promptRegistry = await config.getPromptRegistry();
96
+ const serverPrompts = promptRegistry.getPromptsByServer(serverName) || [];
97
+
98
+ const originalStatus = getMCPServerStatus(serverName);
99
+ const hasCachedItems = serverTools.length > 0 || serverPrompts.length > 0;
100
+
101
+ // If the server is "disconnected" but has prompts or cached tools, display it as Ready
102
+ // by using CONNECTED as the display status.
103
+ const status =
104
+ originalStatus === MCPServerStatus.DISCONNECTED && hasCachedItems
105
+ ? MCPServerStatus.CONNECTED
106
+ : originalStatus;
107
+
108
+ // Add status indicator with descriptive text
109
+ let statusIndicator = '';
110
+ let statusText = '';
111
+ switch (status) {
112
+ case MCPServerStatus.CONNECTED:
113
+ statusIndicator = '🟢';
114
+ statusText = 'Ready';
115
+ break;
116
+ case MCPServerStatus.CONNECTING:
117
+ statusIndicator = '🔄';
118
+ statusText = 'Starting... (first startup may take longer)';
119
+ break;
120
+ case MCPServerStatus.DISCONNECTED:
121
+ default:
122
+ statusIndicator = '🔴';
123
+ statusText = 'Disconnected';
124
+ break;
125
+ }
126
+
127
+ // Get server description if available
128
+ const server = mcpServers[serverName];
129
+ let serverDisplayName = serverName;
130
+ if (server.extensionName) {
131
+ serverDisplayName += ` (from ${server.extensionName})`;
132
+ }
133
+
134
+ // Format server header with bold formatting and status
135
+ message += `${statusIndicator} \u001b[1m${serverDisplayName}\u001b[0m - ${statusText}`;
136
+
137
+ let needsAuthHint = mcpServerRequiresOAuth.get(serverName) || false;
138
+ // Add OAuth status if applicable
139
+ if (server?.oauth?.enabled) {
140
+ needsAuthHint = true;
141
+ try {
142
+ const { MCPOAuthTokenStorage } = await import(
143
+ '@qwen-code/qwen-code-core'
144
+ );
145
+ const hasToken = await MCPOAuthTokenStorage.getToken(serverName);
146
+ if (hasToken) {
147
+ const isExpired = MCPOAuthTokenStorage.isTokenExpired(hasToken.token);
148
+ if (isExpired) {
149
+ message += ` ${COLOR_YELLOW}(OAuth token expired)${RESET_COLOR}`;
150
+ } else {
151
+ message += ` ${COLOR_GREEN}(OAuth authenticated)${RESET_COLOR}`;
152
+ needsAuthHint = false;
153
+ }
154
+ } else {
155
+ message += ` ${COLOR_RED}(OAuth not authenticated)${RESET_COLOR}`;
156
+ }
157
+ } catch (_err) {
158
+ // If we can't check OAuth status, just continue
159
+ }
160
+ }
161
+
162
+ // Add tool count with conditional messaging
163
+ if (status === MCPServerStatus.CONNECTED) {
164
+ const parts = [];
165
+ if (serverTools.length > 0) {
166
+ parts.push(
167
+ `${serverTools.length} ${serverTools.length === 1 ? 'tool' : 'tools'}`,
168
+ );
169
+ }
170
+ if (serverPrompts.length > 0) {
171
+ parts.push(
172
+ `${serverPrompts.length} ${
173
+ serverPrompts.length === 1 ? 'prompt' : 'prompts'
174
+ }`,
175
+ );
176
+ }
177
+ if (parts.length > 0) {
178
+ message += ` (${parts.join(', ')})`;
179
+ } else {
180
+ message += ` (0 tools)`;
181
+ }
182
+ } else if (status === MCPServerStatus.CONNECTING) {
183
+ message += ` (tools and prompts will appear when ready)`;
184
+ } else {
185
+ message += ` (${serverTools.length} tools cached)`;
186
+ }
187
+
188
+ // Add server description with proper handling of multi-line descriptions
189
+ if (showDescriptions && server?.description) {
190
+ const descLines = server.description.trim().split('\n');
191
+ if (descLines) {
192
+ message += ':\n';
193
+ for (const descLine of descLines) {
194
+ message += ` ${COLOR_GREEN}${descLine}${RESET_COLOR}\n`;
195
+ }
196
+ } else {
197
+ message += '\n';
198
+ }
199
+ } else {
200
+ message += '\n';
201
+ }
202
+
203
+ // Reset formatting after server entry
204
+ message += RESET_COLOR;
205
+
206
+ if (serverTools.length > 0) {
207
+ message += ` ${COLOR_CYAN}Tools:${RESET_COLOR}\n`;
208
+ serverTools.forEach((tool) => {
209
+ if (showDescriptions && tool.description) {
210
+ // Format tool name in cyan using simple ANSI cyan color
211
+ message += ` - ${COLOR_CYAN}${tool.name}${RESET_COLOR}`;
212
+
213
+ // Handle multi-line descriptions by properly indenting and preserving formatting
214
+ const descLines = tool.description.trim().split('\n');
215
+ if (descLines) {
216
+ message += ':\n';
217
+ for (const descLine of descLines) {
218
+ message += ` ${COLOR_GREEN}${descLine}${RESET_COLOR}\n`;
219
+ }
220
+ } else {
221
+ message += '\n';
222
+ }
223
+ // Reset is handled inline with each line now
224
+ } else {
225
+ // Use cyan color for the tool name even when not showing descriptions
226
+ message += ` - ${COLOR_CYAN}${tool.name}${RESET_COLOR}\n`;
227
+ }
228
+ const parameters =
229
+ tool.schema.parametersJsonSchema ?? tool.schema.parameters;
230
+ if (showSchema && parameters) {
231
+ // Prefix the parameters in cyan
232
+ message += ` ${COLOR_CYAN}Parameters:${RESET_COLOR}\n`;
233
+
234
+ const paramsLines = JSON.stringify(parameters, null, 2)
235
+ .trim()
236
+ .split('\n');
237
+ if (paramsLines) {
238
+ for (const paramsLine of paramsLines) {
239
+ message += ` ${COLOR_GREEN}${paramsLine}${RESET_COLOR}\n`;
240
+ }
241
+ }
242
+ }
243
+ });
244
+ }
245
+ if (serverPrompts.length > 0) {
246
+ if (serverTools.length > 0) {
247
+ message += '\n';
248
+ }
249
+ message += ` ${COLOR_CYAN}Prompts:${RESET_COLOR}\n`;
250
+ serverPrompts.forEach((prompt: DiscoveredMCPPrompt) => {
251
+ if (showDescriptions && prompt.description) {
252
+ message += ` - ${COLOR_CYAN}${prompt.name}${RESET_COLOR}`;
253
+ const descLines = prompt.description.trim().split('\n');
254
+ if (descLines) {
255
+ message += ':\n';
256
+ for (const descLine of descLines) {
257
+ message += ` ${COLOR_GREEN}${descLine}${RESET_COLOR}\n`;
258
+ }
259
+ } else {
260
+ message += '\n';
261
+ }
262
+ } else {
263
+ message += ` - ${COLOR_CYAN}${prompt.name}${RESET_COLOR}\n`;
264
+ }
265
+ });
266
+ }
267
+
268
+ if (serverTools.length === 0 && serverPrompts.length === 0) {
269
+ message += ' No tools or prompts available\n';
270
+ } else if (serverTools.length === 0) {
271
+ message += ' No tools available';
272
+ if (originalStatus === MCPServerStatus.DISCONNECTED && needsAuthHint) {
273
+ message += ` ${COLOR_GREY}(type: "/mcp auth ${serverName}" to authenticate this server)${RESET_COLOR}`;
274
+ }
275
+ message += '\n';
276
+ } else if (
277
+ originalStatus === MCPServerStatus.DISCONNECTED &&
278
+ needsAuthHint
279
+ ) {
280
+ // This case is for when serverTools.length > 0
281
+ message += ` ${COLOR_GREY}(type: "/mcp auth ${serverName}" to authenticate this server)${RESET_COLOR}\n`;
282
+ }
283
+ message += '\n';
284
+ }
285
+
286
+ for (const server of blockedMcpServers) {
287
+ let serverDisplayName = server.name;
288
+ if (server.extensionName) {
289
+ serverDisplayName += ` (from ${server.extensionName})`;
290
+ }
291
+ message += `🔴 \u001b[1m${serverDisplayName}\u001b[0m - Blocked\n\n`;
292
+ }
293
+
294
+ // Add helpful tips when no arguments are provided
295
+ if (showTips) {
296
+ message += '\n';
297
+ message += `${COLOR_CYAN}💡 Tips:${RESET_COLOR}\n`;
298
+ message += ` • Use ${COLOR_CYAN}/mcp desc${RESET_COLOR} to show server and tool descriptions\n`;
299
+ message += ` • Use ${COLOR_CYAN}/mcp schema${RESET_COLOR} to show tool parameter schemas\n`;
300
+ message += ` • Use ${COLOR_CYAN}/mcp nodesc${RESET_COLOR} to hide descriptions\n`;
301
+ message += ` • Use ${COLOR_CYAN}/mcp auth <server-name>${RESET_COLOR} to authenticate with OAuth-enabled servers\n`;
302
+ message += ` • Press ${COLOR_CYAN}Ctrl+T${RESET_COLOR} to toggle tool descriptions on/off\n`;
303
+ message += '\n';
304
+ }
305
+
306
+ // Make sure to reset any ANSI formatting at the end to prevent it from affecting the terminal
307
+ message += RESET_COLOR;
308
+
309
+ return {
310
+ type: 'message',
311
+ messageType: 'info',
312
+ content: message,
313
+ };
314
+ };
315
+
316
+ const authCommand: SlashCommand = {
317
+ name: 'auth',
318
+ description: 'Authenticate with an OAuth-enabled MCP server',
319
+ kind: CommandKind.BUILT_IN,
320
+ action: async (
321
+ context: CommandContext,
322
+ args: string,
323
+ ): Promise<MessageActionReturn> => {
324
+ const serverName = args.trim();
325
+ const { config } = context.services;
326
+
327
+ if (!config) {
328
+ return {
329
+ type: 'message',
330
+ messageType: 'error',
331
+ content: 'Config not loaded.',
332
+ };
333
+ }
334
+
335
+ const mcpServers = config.getMcpServers() || {};
336
+
337
+ if (!serverName) {
338
+ // List servers that support OAuth
339
+ const oauthServers = Object.entries(mcpServers)
340
+ .filter(([_, server]) => server.oauth?.enabled)
341
+ .map(([name, _]) => name);
342
+
343
+ if (oauthServers.length === 0) {
344
+ return {
345
+ type: 'message',
346
+ messageType: 'info',
347
+ content: 'No MCP servers configured with OAuth authentication.',
348
+ };
349
+ }
350
+
351
+ return {
352
+ type: 'message',
353
+ messageType: 'info',
354
+ content: `MCP servers with OAuth authentication:\n${oauthServers.map((s) => ` - ${s}`).join('\n')}\n\nUse /mcp auth <server-name> to authenticate.`,
355
+ };
356
+ }
357
+
358
+ const server = mcpServers[serverName];
359
+ if (!server) {
360
+ return {
361
+ type: 'message',
362
+ messageType: 'error',
363
+ content: `MCP server '${serverName}' not found.`,
364
+ };
365
+ }
366
+
367
+ // Always attempt OAuth authentication, even if not explicitly configured
368
+ // The authentication process will discover OAuth requirements automatically
369
+
370
+ try {
371
+ context.ui.addItem(
372
+ {
373
+ type: 'info',
374
+ text: `Starting OAuth authentication for MCP server '${serverName}'...`,
375
+ },
376
+ Date.now(),
377
+ );
378
+
379
+ // Import dynamically to avoid circular dependencies
380
+ const { MCPOAuthProvider } = await import('@qwen-code/qwen-code-core');
381
+
382
+ let oauthConfig = server.oauth;
383
+ if (!oauthConfig) {
384
+ oauthConfig = { enabled: false };
385
+ }
386
+
387
+ // Pass the MCP server URL for OAuth discovery
388
+ const mcpServerUrl = server.httpUrl || server.url;
389
+ await MCPOAuthProvider.authenticate(
390
+ serverName,
391
+ oauthConfig,
392
+ mcpServerUrl,
393
+ );
394
+
395
+ context.ui.addItem(
396
+ {
397
+ type: 'info',
398
+ text: `✅ Successfully authenticated with MCP server '${serverName}'!`,
399
+ },
400
+ Date.now(),
401
+ );
402
+
403
+ // Trigger tool re-discovery to pick up authenticated server
404
+ const toolRegistry = config.getToolRegistry();
405
+ if (toolRegistry) {
406
+ context.ui.addItem(
407
+ {
408
+ type: 'info',
409
+ text: `Re-discovering tools from '${serverName}'...`,
410
+ },
411
+ Date.now(),
412
+ );
413
+ await toolRegistry.discoverToolsForServer(serverName);
414
+ }
415
+ // Update the client with the new tools
416
+ const geminiClient = config.getGeminiClient();
417
+ if (geminiClient) {
418
+ await geminiClient.setTools();
419
+ }
420
+
421
+ // Reload the slash commands to reflect the changes.
422
+ context.ui.reloadCommands();
423
+
424
+ return {
425
+ type: 'message',
426
+ messageType: 'info',
427
+ content: `Successfully authenticated and refreshed tools for '${serverName}'.`,
428
+ };
429
+ } catch (error) {
430
+ return {
431
+ type: 'message',
432
+ messageType: 'error',
433
+ content: `Failed to authenticate with MCP server '${serverName}': ${getErrorMessage(error)}`,
434
+ };
435
+ }
436
+ },
437
+ completion: async (context: CommandContext, partialArg: string) => {
438
+ const { config } = context.services;
439
+ if (!config) return [];
440
+
441
+ const mcpServers = config.getMcpServers() || {};
442
+ return Object.keys(mcpServers).filter((name) =>
443
+ name.startsWith(partialArg),
444
+ );
445
+ },
446
+ };
447
+
448
+ const listCommand: SlashCommand = {
449
+ name: 'list',
450
+ description: 'List configured MCP servers and tools',
451
+ kind: CommandKind.BUILT_IN,
452
+ action: async (context: CommandContext, args: string) => {
453
+ const lowerCaseArgs = args.toLowerCase().split(/\s+/).filter(Boolean);
454
+
455
+ const hasDesc =
456
+ lowerCaseArgs.includes('desc') || lowerCaseArgs.includes('descriptions');
457
+ const hasNodesc =
458
+ lowerCaseArgs.includes('nodesc') ||
459
+ lowerCaseArgs.includes('nodescriptions');
460
+ const showSchema = lowerCaseArgs.includes('schema');
461
+
462
+ // Show descriptions if `desc` or `schema` is present,
463
+ // but `nodesc` takes precedence and disables them.
464
+ const showDescriptions = !hasNodesc && (hasDesc || showSchema);
465
+
466
+ // Show tips only when no arguments are provided
467
+ const showTips = lowerCaseArgs.length === 0;
468
+
469
+ return getMcpStatus(context, showDescriptions, showSchema, showTips);
470
+ },
471
+ };
472
+
473
+ const refreshCommand: SlashCommand = {
474
+ name: 'refresh',
475
+ description: 'Restarts MCP servers.',
476
+ kind: CommandKind.BUILT_IN,
477
+ action: async (
478
+ context: CommandContext,
479
+ ): Promise<SlashCommandActionReturn> => {
480
+ const { config } = context.services;
481
+ if (!config) {
482
+ return {
483
+ type: 'message',
484
+ messageType: 'error',
485
+ content: 'Config not loaded.',
486
+ };
487
+ }
488
+
489
+ const toolRegistry = config.getToolRegistry();
490
+ if (!toolRegistry) {
491
+ return {
492
+ type: 'message',
493
+ messageType: 'error',
494
+ content: 'Could not retrieve tool registry.',
495
+ };
496
+ }
497
+
498
+ context.ui.addItem(
499
+ {
500
+ type: 'info',
501
+ text: 'Restarting MCP servers...',
502
+ },
503
+ Date.now(),
504
+ );
505
+
506
+ await toolRegistry.restartMcpServers();
507
+
508
+ // Update the client with the new tools
509
+ const geminiClient = config.getGeminiClient();
510
+ if (geminiClient) {
511
+ await geminiClient.setTools();
512
+ }
513
+
514
+ // Reload the slash commands to reflect the changes.
515
+ context.ui.reloadCommands();
516
+
517
+ return getMcpStatus(context, false, false, false);
518
+ },
519
+ };
520
+
521
+ export const mcpCommand: SlashCommand = {
522
+ name: 'mcp',
523
+ description:
524
+ 'list configured MCP servers and tools, or authenticate with OAuth-enabled servers',
525
+ kind: CommandKind.BUILT_IN,
526
+ subCommands: [listCommand, authCommand, refreshCommand],
527
+ // Default action when no subcommand is provided
528
+ action: async (context: CommandContext, args: string) =>
529
+ // If no subcommand, run the list command
530
+ listCommand.action!(context, args),
531
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/memoryCommand.test.ts ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, Mock } from 'vitest';
8
+ import { memoryCommand } from './memoryCommand.js';
9
+ import { type CommandContext, SlashCommand } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+ import { MessageType } from '../types.js';
12
+ import { LoadedSettings } from '../../config/settings.js';
13
+ import {
14
+ getErrorMessage,
15
+ loadServerHierarchicalMemory,
16
+ type FileDiscoveryService,
17
+ } from '@qwen-code/qwen-code-core';
18
+
19
+ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
20
+ const original =
21
+ await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
22
+ return {
23
+ ...original,
24
+ getErrorMessage: vi.fn((error: unknown) => {
25
+ if (error instanceof Error) return error.message;
26
+ return String(error);
27
+ }),
28
+ loadServerHierarchicalMemory: vi.fn(),
29
+ };
30
+ });
31
+
32
+ const mockLoadServerHierarchicalMemory = loadServerHierarchicalMemory as Mock;
33
+
34
+ describe('memoryCommand', () => {
35
+ let mockContext: CommandContext;
36
+
37
+ const getSubCommand = (name: 'show' | 'add' | 'refresh'): SlashCommand => {
38
+ const subCommand = memoryCommand.subCommands?.find(
39
+ (cmd) => cmd.name === name,
40
+ );
41
+ if (!subCommand) {
42
+ throw new Error(`/memory ${name} command not found.`);
43
+ }
44
+ return subCommand;
45
+ };
46
+
47
+ describe('/memory show', () => {
48
+ let showCommand: SlashCommand;
49
+ let mockGetUserMemory: Mock;
50
+ let mockGetGeminiMdFileCount: Mock;
51
+
52
+ beforeEach(() => {
53
+ showCommand = getSubCommand('show');
54
+
55
+ mockGetUserMemory = vi.fn();
56
+ mockGetGeminiMdFileCount = vi.fn();
57
+
58
+ mockContext = createMockCommandContext({
59
+ services: {
60
+ config: {
61
+ getUserMemory: mockGetUserMemory,
62
+ getGeminiMdFileCount: mockGetGeminiMdFileCount,
63
+ },
64
+ },
65
+ });
66
+ });
67
+
68
+ it('should display a message if memory is empty', async () => {
69
+ if (!showCommand.action) throw new Error('Command has no action');
70
+
71
+ mockGetUserMemory.mockReturnValue('');
72
+ mockGetGeminiMdFileCount.mockReturnValue(0);
73
+
74
+ await showCommand.action(mockContext, '');
75
+
76
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
77
+ {
78
+ type: MessageType.INFO,
79
+ text: 'Memory is currently empty.',
80
+ },
81
+ expect.any(Number),
82
+ );
83
+ });
84
+
85
+ it('should display the memory content and file count if it exists', async () => {
86
+ if (!showCommand.action) throw new Error('Command has no action');
87
+
88
+ const memoryContent = 'This is a test memory.';
89
+
90
+ mockGetUserMemory.mockReturnValue(memoryContent);
91
+ mockGetGeminiMdFileCount.mockReturnValue(1);
92
+
93
+ await showCommand.action(mockContext, '');
94
+
95
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
96
+ {
97
+ type: MessageType.INFO,
98
+ text: `Current memory content from 1 file(s):\n\n---\n${memoryContent}\n---`,
99
+ },
100
+ expect.any(Number),
101
+ );
102
+ });
103
+ });
104
+
105
+ describe('/memory add', () => {
106
+ let addCommand: SlashCommand;
107
+
108
+ beforeEach(() => {
109
+ addCommand = getSubCommand('add');
110
+ mockContext = createMockCommandContext();
111
+ });
112
+
113
+ it('should return an error message if no arguments are provided', () => {
114
+ if (!addCommand.action) throw new Error('Command has no action');
115
+
116
+ const result = addCommand.action(mockContext, ' ');
117
+ expect(result).toEqual({
118
+ type: 'message',
119
+ messageType: 'error',
120
+ content: 'Usage: /memory add [--global|--project] <text to remember>',
121
+ });
122
+
123
+ expect(mockContext.ui.addItem).not.toHaveBeenCalled();
124
+ });
125
+
126
+ it('should return a tool action and add an info message when arguments are provided', () => {
127
+ if (!addCommand.action) throw new Error('Command has no action');
128
+
129
+ const fact = 'remember this';
130
+ const result = addCommand.action(mockContext, ` ${fact} `);
131
+
132
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
133
+ {
134
+ type: MessageType.INFO,
135
+ text: `Attempting to save to memory : "${fact}"`,
136
+ },
137
+ expect.any(Number),
138
+ );
139
+
140
+ expect(result).toEqual({
141
+ type: 'tool',
142
+ toolName: 'save_memory',
143
+ toolArgs: { fact },
144
+ });
145
+ });
146
+
147
+ it('should handle --global flag and add scope to tool args', () => {
148
+ if (!addCommand.action) throw new Error('Command has no action');
149
+
150
+ const fact = 'remember this globally';
151
+ const result = addCommand.action(mockContext, `--global ${fact}`);
152
+
153
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
154
+ {
155
+ type: MessageType.INFO,
156
+ text: `Attempting to save to memory (global): "${fact}"`,
157
+ },
158
+ expect.any(Number),
159
+ );
160
+
161
+ expect(result).toEqual({
162
+ type: 'tool',
163
+ toolName: 'save_memory',
164
+ toolArgs: { fact, scope: 'global' },
165
+ });
166
+ });
167
+
168
+ it('should handle --project flag and add scope to tool args', () => {
169
+ if (!addCommand.action) throw new Error('Command has no action');
170
+
171
+ const fact = 'remember this for project';
172
+ const result = addCommand.action(mockContext, `--project ${fact}`);
173
+
174
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
175
+ {
176
+ type: MessageType.INFO,
177
+ text: `Attempting to save to memory (project): "${fact}"`,
178
+ },
179
+ expect.any(Number),
180
+ );
181
+
182
+ expect(result).toEqual({
183
+ type: 'tool',
184
+ toolName: 'save_memory',
185
+ toolArgs: { fact, scope: 'project' },
186
+ });
187
+ });
188
+
189
+ it('should return error if flag is provided but no fact follows', () => {
190
+ if (!addCommand.action) throw new Error('Command has no action');
191
+
192
+ const result = addCommand.action(mockContext, '--global ');
193
+ expect(result).toEqual({
194
+ type: 'message',
195
+ messageType: 'error',
196
+ content: 'Usage: /memory add [--global|--project] <text to remember>',
197
+ });
198
+
199
+ expect(mockContext.ui.addItem).not.toHaveBeenCalled();
200
+ });
201
+ });
202
+
203
+ describe('/memory refresh', () => {
204
+ let refreshCommand: SlashCommand;
205
+ let mockSetUserMemory: Mock;
206
+ let mockSetGeminiMdFileCount: Mock;
207
+
208
+ beforeEach(() => {
209
+ refreshCommand = getSubCommand('refresh');
210
+ mockSetUserMemory = vi.fn();
211
+ mockSetGeminiMdFileCount = vi.fn();
212
+ const mockConfig = {
213
+ setUserMemory: mockSetUserMemory,
214
+ setGeminiMdFileCount: mockSetGeminiMdFileCount,
215
+ getWorkingDir: () => '/test/dir',
216
+ getDebugMode: () => false,
217
+ getFileService: () => ({}) as FileDiscoveryService,
218
+ getExtensionContextFilePaths: () => [],
219
+ shouldLoadMemoryFromIncludeDirectories: () => false,
220
+ getWorkspaceContext: () => ({
221
+ getDirectories: () => [],
222
+ }),
223
+ getFileFilteringOptions: () => ({
224
+ ignore: [],
225
+ include: [],
226
+ }),
227
+ };
228
+
229
+ mockContext = createMockCommandContext({
230
+ services: {
231
+ config: mockConfig,
232
+ settings: {
233
+ merged: {
234
+ memoryDiscoveryMaxDirs: 1000,
235
+ },
236
+ } as LoadedSettings,
237
+ },
238
+ });
239
+ mockLoadServerHierarchicalMemory.mockClear();
240
+ });
241
+
242
+ it('should display success message when memory is refreshed with content', async () => {
243
+ if (!refreshCommand.action) throw new Error('Command has no action');
244
+
245
+ const refreshResult = {
246
+ memoryContent: 'new memory content',
247
+ fileCount: 2,
248
+ };
249
+ mockLoadServerHierarchicalMemory.mockResolvedValue(refreshResult);
250
+
251
+ await refreshCommand.action(mockContext, '');
252
+
253
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
254
+ {
255
+ type: MessageType.INFO,
256
+ text: 'Refreshing memory from source files...',
257
+ },
258
+ expect.any(Number),
259
+ );
260
+
261
+ expect(loadServerHierarchicalMemory).toHaveBeenCalledOnce();
262
+ expect(mockSetUserMemory).toHaveBeenCalledWith(
263
+ refreshResult.memoryContent,
264
+ );
265
+ expect(mockSetGeminiMdFileCount).toHaveBeenCalledWith(
266
+ refreshResult.fileCount,
267
+ );
268
+
269
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
270
+ {
271
+ type: MessageType.INFO,
272
+ text: 'Memory refreshed successfully. Loaded 18 characters from 2 file(s).',
273
+ },
274
+ expect.any(Number),
275
+ );
276
+ });
277
+
278
+ it('should display success message when memory is refreshed with no content', async () => {
279
+ if (!refreshCommand.action) throw new Error('Command has no action');
280
+
281
+ const refreshResult = { memoryContent: '', fileCount: 0 };
282
+ mockLoadServerHierarchicalMemory.mockResolvedValue(refreshResult);
283
+
284
+ await refreshCommand.action(mockContext, '');
285
+
286
+ expect(loadServerHierarchicalMemory).toHaveBeenCalledOnce();
287
+ expect(mockSetUserMemory).toHaveBeenCalledWith('');
288
+ expect(mockSetGeminiMdFileCount).toHaveBeenCalledWith(0);
289
+
290
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
291
+ {
292
+ type: MessageType.INFO,
293
+ text: 'Memory refreshed successfully. No memory content found.',
294
+ },
295
+ expect.any(Number),
296
+ );
297
+ });
298
+
299
+ it('should display an error message if refreshing fails', async () => {
300
+ if (!refreshCommand.action) throw new Error('Command has no action');
301
+
302
+ const error = new Error('Failed to read memory files.');
303
+ mockLoadServerHierarchicalMemory.mockRejectedValue(error);
304
+
305
+ await refreshCommand.action(mockContext, '');
306
+
307
+ expect(loadServerHierarchicalMemory).toHaveBeenCalledOnce();
308
+ expect(mockSetUserMemory).not.toHaveBeenCalled();
309
+ expect(mockSetGeminiMdFileCount).not.toHaveBeenCalled();
310
+
311
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
312
+ {
313
+ type: MessageType.ERROR,
314
+ text: `Error refreshing memory: ${error.message}`,
315
+ },
316
+ expect.any(Number),
317
+ );
318
+
319
+ expect(getErrorMessage).toHaveBeenCalledWith(error);
320
+ });
321
+
322
+ it('should not throw if config service is unavailable', async () => {
323
+ if (!refreshCommand.action) throw new Error('Command has no action');
324
+
325
+ const nullConfigContext = createMockCommandContext({
326
+ services: { config: null },
327
+ });
328
+
329
+ await expect(
330
+ refreshCommand.action(nullConfigContext, ''),
331
+ ).resolves.toBeUndefined();
332
+
333
+ expect(nullConfigContext.ui.addItem).toHaveBeenCalledWith(
334
+ {
335
+ type: MessageType.INFO,
336
+ text: 'Refreshing memory from source files...',
337
+ },
338
+ expect.any(Number),
339
+ );
340
+
341
+ expect(loadServerHierarchicalMemory).not.toHaveBeenCalled();
342
+ });
343
+ });
344
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/memoryCommand.ts ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ getErrorMessage,
9
+ loadServerHierarchicalMemory,
10
+ QWEN_DIR,
11
+ } from '@qwen-code/qwen-code-core';
12
+ import path from 'node:path';
13
+ import os from 'os';
14
+ import fs from 'fs/promises';
15
+ import { MessageType } from '../types.js';
16
+ import {
17
+ CommandKind,
18
+ SlashCommand,
19
+ SlashCommandActionReturn,
20
+ } from './types.js';
21
+
22
+ export const memoryCommand: SlashCommand = {
23
+ name: 'memory',
24
+ description: 'Commands for interacting with memory.',
25
+ kind: CommandKind.BUILT_IN,
26
+ subCommands: [
27
+ {
28
+ name: 'show',
29
+ description: 'Show the current memory contents.',
30
+ kind: CommandKind.BUILT_IN,
31
+ action: async (context) => {
32
+ const memoryContent = context.services.config?.getUserMemory() || '';
33
+ const fileCount = context.services.config?.getGeminiMdFileCount() || 0;
34
+
35
+ const messageContent =
36
+ memoryContent.length > 0
37
+ ? `Current memory content from ${fileCount} file(s):\n\n---\n${memoryContent}\n---`
38
+ : 'Memory is currently empty.';
39
+
40
+ context.ui.addItem(
41
+ {
42
+ type: MessageType.INFO,
43
+ text: messageContent,
44
+ },
45
+ Date.now(),
46
+ );
47
+ },
48
+ subCommands: [
49
+ {
50
+ name: '--project',
51
+ description: 'Show project-level memory contents.',
52
+ kind: CommandKind.BUILT_IN,
53
+ action: async (context) => {
54
+ try {
55
+ const projectMemoryPath = path.join(process.cwd(), 'QWEN.md');
56
+ const memoryContent = await fs.readFile(
57
+ projectMemoryPath,
58
+ 'utf-8',
59
+ );
60
+
61
+ const messageContent =
62
+ memoryContent.trim().length > 0
63
+ ? `Project memory content from ${projectMemoryPath}:\n\n---\n${memoryContent}\n---`
64
+ : 'Project memory is currently empty.';
65
+
66
+ context.ui.addItem(
67
+ {
68
+ type: MessageType.INFO,
69
+ text: messageContent,
70
+ },
71
+ Date.now(),
72
+ );
73
+ } catch (_error) {
74
+ context.ui.addItem(
75
+ {
76
+ type: MessageType.INFO,
77
+ text: 'Project memory file not found or is currently empty.',
78
+ },
79
+ Date.now(),
80
+ );
81
+ }
82
+ },
83
+ },
84
+ {
85
+ name: '--global',
86
+ description: 'Show global memory contents.',
87
+ kind: CommandKind.BUILT_IN,
88
+ action: async (context) => {
89
+ try {
90
+ const globalMemoryPath = path.join(
91
+ os.homedir(),
92
+ QWEN_DIR,
93
+ 'QWEN.md',
94
+ );
95
+ const globalMemoryContent = await fs.readFile(
96
+ globalMemoryPath,
97
+ 'utf-8',
98
+ );
99
+
100
+ const messageContent =
101
+ globalMemoryContent.trim().length > 0
102
+ ? `Global memory content:\n\n---\n${globalMemoryContent}\n---`
103
+ : 'Global memory is currently empty.';
104
+
105
+ context.ui.addItem(
106
+ {
107
+ type: MessageType.INFO,
108
+ text: messageContent,
109
+ },
110
+ Date.now(),
111
+ );
112
+ } catch (_error) {
113
+ context.ui.addItem(
114
+ {
115
+ type: MessageType.INFO,
116
+ text: 'Global memory file not found or is currently empty.',
117
+ },
118
+ Date.now(),
119
+ );
120
+ }
121
+ },
122
+ },
123
+ ],
124
+ },
125
+ {
126
+ name: 'add',
127
+ description:
128
+ 'Add content to the memory. Use --global for global memory or --project for project memory.',
129
+ kind: CommandKind.BUILT_IN,
130
+ action: (context, args): SlashCommandActionReturn | void => {
131
+ if (!args || args.trim() === '') {
132
+ return {
133
+ type: 'message',
134
+ messageType: 'error',
135
+ content:
136
+ 'Usage: /memory add [--global|--project] <text to remember>',
137
+ };
138
+ }
139
+
140
+ const trimmedArgs = args.trim();
141
+ let scope: 'global' | 'project' | undefined;
142
+ let fact: string;
143
+
144
+ // Check for scope flags
145
+ if (trimmedArgs.startsWith('--global ')) {
146
+ scope = 'global';
147
+ fact = trimmedArgs.substring('--global '.length).trim();
148
+ } else if (trimmedArgs.startsWith('--project ')) {
149
+ scope = 'project';
150
+ fact = trimmedArgs.substring('--project '.length).trim();
151
+ } else if (trimmedArgs === '--global' || trimmedArgs === '--project') {
152
+ // Flag provided but no text after it
153
+ return {
154
+ type: 'message',
155
+ messageType: 'error',
156
+ content:
157
+ 'Usage: /memory add [--global|--project] <text to remember>',
158
+ };
159
+ } else {
160
+ // No scope specified, will be handled by the tool
161
+ fact = trimmedArgs;
162
+ }
163
+
164
+ if (!fact || fact.trim() === '') {
165
+ return {
166
+ type: 'message',
167
+ messageType: 'error',
168
+ content:
169
+ 'Usage: /memory add [--global|--project] <text to remember>',
170
+ };
171
+ }
172
+
173
+ const scopeText = scope ? `(${scope})` : '';
174
+ context.ui.addItem(
175
+ {
176
+ type: MessageType.INFO,
177
+ text: `Attempting to save to memory ${scopeText}: "${fact}"`,
178
+ },
179
+ Date.now(),
180
+ );
181
+
182
+ return {
183
+ type: 'tool',
184
+ toolName: 'save_memory',
185
+ toolArgs: scope ? { fact, scope } : { fact },
186
+ };
187
+ },
188
+ subCommands: [
189
+ {
190
+ name: '--project',
191
+ description: 'Add content to project-level memory.',
192
+ kind: CommandKind.BUILT_IN,
193
+ action: (context, args): SlashCommandActionReturn | void => {
194
+ if (!args || args.trim() === '') {
195
+ return {
196
+ type: 'message',
197
+ messageType: 'error',
198
+ content: 'Usage: /memory add --project <text to remember>',
199
+ };
200
+ }
201
+
202
+ context.ui.addItem(
203
+ {
204
+ type: MessageType.INFO,
205
+ text: `Attempting to save to project memory: "${args.trim()}"`,
206
+ },
207
+ Date.now(),
208
+ );
209
+
210
+ return {
211
+ type: 'tool',
212
+ toolName: 'save_memory',
213
+ toolArgs: { fact: args.trim(), scope: 'project' },
214
+ };
215
+ },
216
+ },
217
+ {
218
+ name: '--global',
219
+ description: 'Add content to global memory.',
220
+ kind: CommandKind.BUILT_IN,
221
+ action: (context, args): SlashCommandActionReturn | void => {
222
+ if (!args || args.trim() === '') {
223
+ return {
224
+ type: 'message',
225
+ messageType: 'error',
226
+ content: 'Usage: /memory add --global <text to remember>',
227
+ };
228
+ }
229
+
230
+ context.ui.addItem(
231
+ {
232
+ type: MessageType.INFO,
233
+ text: `Attempting to save to global memory: "${args.trim()}"`,
234
+ },
235
+ Date.now(),
236
+ );
237
+
238
+ return {
239
+ type: 'tool',
240
+ toolName: 'save_memory',
241
+ toolArgs: { fact: args.trim(), scope: 'global' },
242
+ };
243
+ },
244
+ },
245
+ ],
246
+ },
247
+ {
248
+ name: 'refresh',
249
+ description: 'Refresh the memory from the source.',
250
+ kind: CommandKind.BUILT_IN,
251
+ action: async (context) => {
252
+ context.ui.addItem(
253
+ {
254
+ type: MessageType.INFO,
255
+ text: 'Refreshing memory from source files...',
256
+ },
257
+ Date.now(),
258
+ );
259
+
260
+ try {
261
+ const config = context.services.config;
262
+ if (config) {
263
+ const { memoryContent, fileCount } =
264
+ await loadServerHierarchicalMemory(
265
+ config.getWorkingDir(),
266
+ config.shouldLoadMemoryFromIncludeDirectories()
267
+ ? config.getWorkspaceContext().getDirectories()
268
+ : [],
269
+ config.getDebugMode(),
270
+ config.getFileService(),
271
+ config.getExtensionContextFilePaths(),
272
+ context.services.settings.merged.memoryImportFormat || 'tree', // Use setting or default to 'tree'
273
+ config.getFileFilteringOptions(),
274
+ context.services.settings.merged.memoryDiscoveryMaxDirs,
275
+ );
276
+ config.setUserMemory(memoryContent);
277
+ config.setGeminiMdFileCount(fileCount);
278
+
279
+ const successMessage =
280
+ memoryContent.length > 0
281
+ ? `Memory refreshed successfully. Loaded ${memoryContent.length} characters from ${fileCount} file(s).`
282
+ : 'Memory refreshed successfully. No memory content found.';
283
+
284
+ context.ui.addItem(
285
+ {
286
+ type: MessageType.INFO,
287
+ text: successMessage,
288
+ },
289
+ Date.now(),
290
+ );
291
+ }
292
+ } catch (error) {
293
+ const errorMessage = getErrorMessage(error);
294
+ context.ui.addItem(
295
+ {
296
+ type: MessageType.ERROR,
297
+ text: `Error refreshing memory: ${errorMessage}`,
298
+ },
299
+ Date.now(),
300
+ );
301
+ }
302
+ },
303
+ },
304
+ ],
305
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/privacyCommand.test.ts ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach } from 'vitest';
8
+ import { privacyCommand } from './privacyCommand.js';
9
+ import { type CommandContext } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+
12
+ describe('privacyCommand', () => {
13
+ let mockContext: CommandContext;
14
+
15
+ beforeEach(() => {
16
+ mockContext = createMockCommandContext();
17
+ });
18
+
19
+ it('should return a dialog action to open the privacy dialog', () => {
20
+ // Ensure the command has an action to test.
21
+ if (!privacyCommand.action) {
22
+ throw new Error('The privacy command must have an action.');
23
+ }
24
+
25
+ const result = privacyCommand.action(mockContext, '');
26
+
27
+ // Assert that the action returns the correct object to trigger the privacy dialog.
28
+ expect(result).toEqual({
29
+ type: 'dialog',
30
+ dialog: 'privacy',
31
+ });
32
+ });
33
+
34
+ it('should have the correct name and description', () => {
35
+ expect(privacyCommand.name).toBe('privacy');
36
+ expect(privacyCommand.description).toBe('display the privacy notice');
37
+ });
38
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/privacyCommand.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { CommandKind, OpenDialogActionReturn, SlashCommand } from './types.js';
8
+
9
+ export const privacyCommand: SlashCommand = {
10
+ name: 'privacy',
11
+ description: 'display the privacy notice',
12
+ kind: CommandKind.BUILT_IN,
13
+ action: (): OpenDialogActionReturn => ({
14
+ type: 'dialog',
15
+ dialog: 'privacy',
16
+ }),
17
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/quitCommand.test.ts ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import { quitCommand } from './quitCommand.js';
9
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
10
+ import { formatDuration } from '../utils/formatters.js';
11
+
12
+ vi.mock('../utils/formatters.js');
13
+
14
+ describe('quitCommand', () => {
15
+ beforeEach(() => {
16
+ vi.useFakeTimers();
17
+ vi.setSystemTime(new Date('2025-01-01T01:00:00Z'));
18
+ vi.mocked(formatDuration).mockReturnValue('1h 0m 0s');
19
+ });
20
+
21
+ afterEach(() => {
22
+ vi.useRealTimers();
23
+ vi.clearAllMocks();
24
+ });
25
+
26
+ it('returns a QuitActionReturn object with the correct messages', () => {
27
+ const mockContext = createMockCommandContext({
28
+ session: {
29
+ stats: {
30
+ sessionStartTime: new Date('2025-01-01T00:00:00Z'),
31
+ },
32
+ },
33
+ });
34
+
35
+ if (!quitCommand.action) throw new Error('Action is not defined');
36
+ const result = quitCommand.action(mockContext, 'quit');
37
+
38
+ expect(formatDuration).toHaveBeenCalledWith(3600000); // 1 hour in ms
39
+ expect(result).toEqual({
40
+ type: 'quit',
41
+ messages: [
42
+ {
43
+ type: 'user',
44
+ text: '/quit',
45
+ id: expect.any(Number),
46
+ },
47
+ {
48
+ type: 'quit',
49
+ duration: '1h 0m 0s',
50
+ id: expect.any(Number),
51
+ },
52
+ ],
53
+ });
54
+ });
55
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/quitCommand.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { formatDuration } from '../utils/formatters.js';
8
+ import { CommandKind, type SlashCommand } from './types.js';
9
+
10
+ export const quitCommand: SlashCommand = {
11
+ name: 'quit',
12
+ altNames: ['exit'],
13
+ description: 'exit the cli',
14
+ kind: CommandKind.BUILT_IN,
15
+ action: (context) => {
16
+ const now = Date.now();
17
+ const { sessionStartTime } = context.session.stats;
18
+ const wallDuration = now - sessionStartTime.getTime();
19
+
20
+ return {
21
+ type: 'quit',
22
+ messages: [
23
+ {
24
+ type: 'user',
25
+ text: `/quit`, // Keep it consistent, even if /exit was used
26
+ id: now - 1,
27
+ },
28
+ {
29
+ type: 'quit',
30
+ duration: formatDuration(wallDuration),
31
+ id: now,
32
+ },
33
+ ],
34
+ };
35
+ },
36
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/restoreCommand.test.ts ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import * as fs from 'fs/promises';
9
+ import * as os from 'os';
10
+ import * as path from 'path';
11
+ import { restoreCommand } from './restoreCommand.js';
12
+ import { type CommandContext } from './types.js';
13
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
14
+ import { Config, GitService } from '@qwen-code/qwen-code-core';
15
+
16
+ describe('restoreCommand', () => {
17
+ let mockContext: CommandContext;
18
+ let mockConfig: Config;
19
+ let mockGitService: GitService;
20
+ let mockSetHistory: ReturnType<typeof vi.fn>;
21
+ let testRootDir: string;
22
+ let geminiTempDir: string;
23
+ let checkpointsDir: string;
24
+
25
+ beforeEach(async () => {
26
+ testRootDir = await fs.mkdtemp(
27
+ path.join(os.tmpdir(), 'restore-command-test-'),
28
+ );
29
+ geminiTempDir = path.join(testRootDir, '.gemini');
30
+ checkpointsDir = path.join(geminiTempDir, 'checkpoints');
31
+ // The command itself creates this, but for tests it's easier to have it ready.
32
+ // Some tests might remove it to test error paths.
33
+ await fs.mkdir(checkpointsDir, { recursive: true });
34
+
35
+ mockSetHistory = vi.fn().mockResolvedValue(undefined);
36
+ mockGitService = {
37
+ restoreProjectFromSnapshot: vi.fn().mockResolvedValue(undefined),
38
+ } as unknown as GitService;
39
+
40
+ mockConfig = {
41
+ getCheckpointingEnabled: vi.fn().mockReturnValue(true),
42
+ getProjectTempDir: vi.fn().mockReturnValue(geminiTempDir),
43
+ getGeminiClient: vi.fn().mockReturnValue({
44
+ setHistory: mockSetHistory,
45
+ }),
46
+ } as unknown as Config;
47
+
48
+ mockContext = createMockCommandContext({
49
+ services: {
50
+ config: mockConfig,
51
+ git: mockGitService,
52
+ },
53
+ });
54
+ });
55
+
56
+ afterEach(async () => {
57
+ vi.restoreAllMocks();
58
+ await fs.rm(testRootDir, { recursive: true, force: true });
59
+ });
60
+
61
+ it('should return null if checkpointing is not enabled', () => {
62
+ vi.mocked(mockConfig.getCheckpointingEnabled).mockReturnValue(false);
63
+
64
+ expect(restoreCommand(mockConfig)).toBeNull();
65
+ });
66
+
67
+ it('should return the command if checkpointing is enabled', () => {
68
+ expect(restoreCommand(mockConfig)).toEqual(
69
+ expect.objectContaining({
70
+ name: 'restore',
71
+ description: expect.any(String),
72
+ action: expect.any(Function),
73
+ completion: expect.any(Function),
74
+ }),
75
+ );
76
+ });
77
+
78
+ describe('action', () => {
79
+ it('should return an error if temp dir is not found', async () => {
80
+ vi.mocked(mockConfig.getProjectTempDir).mockReturnValue('');
81
+
82
+ expect(
83
+ await restoreCommand(mockConfig)?.action?.(mockContext, ''),
84
+ ).toEqual({
85
+ type: 'message',
86
+ messageType: 'error',
87
+ content: 'Could not determine the .gemini directory path.',
88
+ });
89
+ });
90
+
91
+ it('should inform when no checkpoints are found if no args are passed', async () => {
92
+ // Remove the directory to ensure the command creates it.
93
+ await fs.rm(checkpointsDir, { recursive: true, force: true });
94
+ const command = restoreCommand(mockConfig);
95
+
96
+ expect(await command?.action?.(mockContext, '')).toEqual({
97
+ type: 'message',
98
+ messageType: 'info',
99
+ content: 'No restorable tool calls found.',
100
+ });
101
+ // Verify the directory was created by the command.
102
+ await expect(fs.stat(checkpointsDir)).resolves.toBeDefined();
103
+ });
104
+
105
+ it('should list available checkpoints if no args are passed', async () => {
106
+ await fs.writeFile(path.join(checkpointsDir, 'test1.json'), '{}');
107
+ await fs.writeFile(path.join(checkpointsDir, 'test2.json'), '{}');
108
+ const command = restoreCommand(mockConfig);
109
+
110
+ expect(await command?.action?.(mockContext, '')).toEqual({
111
+ type: 'message',
112
+ messageType: 'info',
113
+ content: 'Available tool calls to restore:\n\ntest1\ntest2',
114
+ });
115
+ });
116
+
117
+ it('should return an error if the specified file is not found', async () => {
118
+ await fs.writeFile(path.join(checkpointsDir, 'test1.json'), '{}');
119
+ const command = restoreCommand(mockConfig);
120
+
121
+ expect(await command?.action?.(mockContext, 'test2')).toEqual({
122
+ type: 'message',
123
+ messageType: 'error',
124
+ content: 'File not found: test2.json',
125
+ });
126
+ });
127
+
128
+ it('should handle file read errors gracefully', async () => {
129
+ const checkpointName = 'test1';
130
+ const checkpointPath = path.join(
131
+ checkpointsDir,
132
+ `${checkpointName}.json`,
133
+ );
134
+ // Create a directory instead of a file to cause a read error.
135
+ await fs.mkdir(checkpointPath);
136
+ const command = restoreCommand(mockConfig);
137
+
138
+ expect(await command?.action?.(mockContext, checkpointName)).toEqual({
139
+ type: 'message',
140
+ messageType: 'error',
141
+ content: expect.stringContaining(
142
+ 'Could not read restorable tool calls.',
143
+ ),
144
+ });
145
+ });
146
+
147
+ it('should restore a tool call and project state', async () => {
148
+ const toolCallData = {
149
+ history: [{ type: 'user', text: 'do a thing' }],
150
+ clientHistory: [{ role: 'user', parts: [{ text: 'do a thing' }] }],
151
+ commitHash: 'abcdef123',
152
+ toolCall: { name: 'run_shell_command', args: 'ls' },
153
+ };
154
+ await fs.writeFile(
155
+ path.join(checkpointsDir, 'my-checkpoint.json'),
156
+ JSON.stringify(toolCallData),
157
+ );
158
+ const command = restoreCommand(mockConfig);
159
+
160
+ expect(await command?.action?.(mockContext, 'my-checkpoint')).toEqual({
161
+ type: 'tool',
162
+ toolName: 'run_shell_command',
163
+ toolArgs: 'ls',
164
+ });
165
+ expect(mockContext.ui.loadHistory).toHaveBeenCalledWith(
166
+ toolCallData.history,
167
+ );
168
+ expect(mockSetHistory).toHaveBeenCalledWith(toolCallData.clientHistory);
169
+ expect(mockGitService.restoreProjectFromSnapshot).toHaveBeenCalledWith(
170
+ toolCallData.commitHash,
171
+ );
172
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
173
+ {
174
+ type: 'info',
175
+ text: 'Restored project to the state before the tool call.',
176
+ },
177
+ expect.any(Number),
178
+ );
179
+ });
180
+
181
+ it('should restore even if only toolCall is present', async () => {
182
+ const toolCallData = {
183
+ toolCall: { name: 'run_shell_command', args: 'ls' },
184
+ };
185
+ await fs.writeFile(
186
+ path.join(checkpointsDir, 'my-checkpoint.json'),
187
+ JSON.stringify(toolCallData),
188
+ );
189
+
190
+ const command = restoreCommand(mockConfig);
191
+
192
+ expect(await command?.action?.(mockContext, 'my-checkpoint')).toEqual({
193
+ type: 'tool',
194
+ toolName: 'run_shell_command',
195
+ toolArgs: 'ls',
196
+ });
197
+
198
+ expect(mockContext.ui.loadHistory).not.toHaveBeenCalled();
199
+ expect(mockSetHistory).not.toHaveBeenCalled();
200
+ expect(mockGitService.restoreProjectFromSnapshot).not.toHaveBeenCalled();
201
+ });
202
+ });
203
+
204
+ it('should return an error for a checkpoint file missing the toolCall property', async () => {
205
+ const checkpointName = 'missing-toolcall';
206
+ await fs.writeFile(
207
+ path.join(checkpointsDir, `${checkpointName}.json`),
208
+ JSON.stringify({ history: [] }), // An object that is valid JSON but missing the 'toolCall' property
209
+ );
210
+ const command = restoreCommand(mockConfig);
211
+
212
+ expect(await command?.action?.(mockContext, checkpointName)).toEqual({
213
+ type: 'message',
214
+ messageType: 'error',
215
+ // A more specific error message would be ideal, but for now, we can assert the current behavior.
216
+ content: expect.stringContaining('Could not read restorable tool calls.'),
217
+ });
218
+ });
219
+
220
+ describe('completion', () => {
221
+ it('should return an empty array if temp dir is not found', async () => {
222
+ vi.mocked(mockConfig.getProjectTempDir).mockReturnValue('');
223
+ const command = restoreCommand(mockConfig);
224
+
225
+ expect(await command?.completion?.(mockContext, '')).toEqual([]);
226
+ });
227
+
228
+ it('should return an empty array on readdir error', async () => {
229
+ await fs.rm(checkpointsDir, { recursive: true, force: true });
230
+ const command = restoreCommand(mockConfig);
231
+
232
+ expect(await command?.completion?.(mockContext, '')).toEqual([]);
233
+ });
234
+
235
+ it('should return a list of checkpoint names', async () => {
236
+ await fs.writeFile(path.join(checkpointsDir, 'test1.json'), '{}');
237
+ await fs.writeFile(path.join(checkpointsDir, 'test2.json'), '{}');
238
+ await fs.writeFile(
239
+ path.join(checkpointsDir, 'not-a-checkpoint.txt'),
240
+ '{}',
241
+ );
242
+ const command = restoreCommand(mockConfig);
243
+
244
+ expect(await command?.completion?.(mockContext, '')).toEqual([
245
+ 'test1',
246
+ 'test2',
247
+ ]);
248
+ });
249
+ });
250
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/restoreCommand.ts ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'fs/promises';
8
+ import path from 'path';
9
+ import {
10
+ type CommandContext,
11
+ type SlashCommand,
12
+ type SlashCommandActionReturn,
13
+ CommandKind,
14
+ } from './types.js';
15
+ import { Config } from '@qwen-code/qwen-code-core';
16
+
17
+ async function restoreAction(
18
+ context: CommandContext,
19
+ args: string,
20
+ ): Promise<void | SlashCommandActionReturn> {
21
+ const { services, ui } = context;
22
+ const { config, git: gitService } = services;
23
+ const { addItem, loadHistory } = ui;
24
+
25
+ const checkpointDir = config?.getProjectTempDir()
26
+ ? path.join(config.getProjectTempDir(), 'checkpoints')
27
+ : undefined;
28
+
29
+ if (!checkpointDir) {
30
+ return {
31
+ type: 'message',
32
+ messageType: 'error',
33
+ content: 'Could not determine the .gemini directory path.',
34
+ };
35
+ }
36
+
37
+ try {
38
+ // Ensure the directory exists before trying to read it.
39
+ await fs.mkdir(checkpointDir, { recursive: true });
40
+ const files = await fs.readdir(checkpointDir);
41
+ const jsonFiles = files.filter((file) => file.endsWith('.json'));
42
+
43
+ if (!args) {
44
+ if (jsonFiles.length === 0) {
45
+ return {
46
+ type: 'message',
47
+ messageType: 'info',
48
+ content: 'No restorable tool calls found.',
49
+ };
50
+ }
51
+ const truncatedFiles = jsonFiles.map((file) => {
52
+ const components = file.split('.');
53
+ if (components.length <= 1) {
54
+ return file;
55
+ }
56
+ components.pop();
57
+ return components.join('.');
58
+ });
59
+ const fileList = truncatedFiles.join('\n');
60
+ return {
61
+ type: 'message',
62
+ messageType: 'info',
63
+ content: `Available tool calls to restore:\n\n${fileList}`,
64
+ };
65
+ }
66
+
67
+ const selectedFile = args.endsWith('.json') ? args : `${args}.json`;
68
+
69
+ if (!jsonFiles.includes(selectedFile)) {
70
+ return {
71
+ type: 'message',
72
+ messageType: 'error',
73
+ content: `File not found: ${selectedFile}`,
74
+ };
75
+ }
76
+
77
+ const filePath = path.join(checkpointDir, selectedFile);
78
+ const data = await fs.readFile(filePath, 'utf-8');
79
+ const toolCallData = JSON.parse(data);
80
+
81
+ if (toolCallData.history) {
82
+ if (!loadHistory) {
83
+ // This should not happen
84
+ return {
85
+ type: 'message',
86
+ messageType: 'error',
87
+ content: 'loadHistory function is not available.',
88
+ };
89
+ }
90
+ loadHistory(toolCallData.history);
91
+ }
92
+
93
+ if (toolCallData.clientHistory) {
94
+ await config?.getGeminiClient()?.setHistory(toolCallData.clientHistory);
95
+ }
96
+
97
+ if (toolCallData.commitHash) {
98
+ await gitService?.restoreProjectFromSnapshot(toolCallData.commitHash);
99
+ addItem(
100
+ {
101
+ type: 'info',
102
+ text: 'Restored project to the state before the tool call.',
103
+ },
104
+ Date.now(),
105
+ );
106
+ }
107
+
108
+ return {
109
+ type: 'tool',
110
+ toolName: toolCallData.toolCall.name,
111
+ toolArgs: toolCallData.toolCall.args,
112
+ };
113
+ } catch (error) {
114
+ return {
115
+ type: 'message',
116
+ messageType: 'error',
117
+ content: `Could not read restorable tool calls. This is the error: ${error}`,
118
+ };
119
+ }
120
+ }
121
+
122
+ async function completion(
123
+ context: CommandContext,
124
+ _partialArg: string,
125
+ ): Promise<string[]> {
126
+ const { services } = context;
127
+ const { config } = services;
128
+ const checkpointDir = config?.getProjectTempDir()
129
+ ? path.join(config.getProjectTempDir(), 'checkpoints')
130
+ : undefined;
131
+ if (!checkpointDir) {
132
+ return [];
133
+ }
134
+ try {
135
+ const files = await fs.readdir(checkpointDir);
136
+ return files
137
+ .filter((file) => file.endsWith('.json'))
138
+ .map((file) => file.replace('.json', ''));
139
+ } catch (_err) {
140
+ return [];
141
+ }
142
+ }
143
+
144
+ export const restoreCommand = (config: Config | null): SlashCommand | null => {
145
+ if (!config?.getCheckpointingEnabled()) {
146
+ return null;
147
+ }
148
+
149
+ return {
150
+ name: 'restore',
151
+ description:
152
+ 'Restore a tool call. This will reset the conversation and file history to the state it was in when the tool call was suggested',
153
+ kind: CommandKind.BUILT_IN,
154
+ action: restoreAction,
155
+ completion,
156
+ };
157
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/settingsCommand.test.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach } from 'vitest';
8
+ import { settingsCommand } from './settingsCommand.js';
9
+ import { type CommandContext } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+
12
+ describe('settingsCommand', () => {
13
+ let mockContext: CommandContext;
14
+
15
+ beforeEach(() => {
16
+ mockContext = createMockCommandContext();
17
+ });
18
+
19
+ it('should return a dialog action to open the settings dialog', () => {
20
+ if (!settingsCommand.action) {
21
+ throw new Error('The settings command must have an action.');
22
+ }
23
+ const result = settingsCommand.action(mockContext, '');
24
+ expect(result).toEqual({
25
+ type: 'dialog',
26
+ dialog: 'settings',
27
+ });
28
+ });
29
+
30
+ it('should have the correct name and description', () => {
31
+ expect(settingsCommand.name).toBe('settings');
32
+ expect(settingsCommand.description).toBe(
33
+ 'View and edit Qwen Code settings',
34
+ );
35
+ });
36
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/settingsCommand.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { CommandKind, OpenDialogActionReturn, SlashCommand } from './types.js';
8
+
9
+ export const settingsCommand: SlashCommand = {
10
+ name: 'settings',
11
+ description: 'View and edit Qwen Code settings',
12
+ kind: CommandKind.BUILT_IN,
13
+ action: (_context, _args): OpenDialogActionReturn => ({
14
+ type: 'dialog',
15
+ dialog: 'settings',
16
+ }),
17
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/setupGithubCommand.test.ts ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ import fs from 'node:fs/promises';
10
+
11
+ import { vi, describe, expect, it, afterEach, beforeEach } from 'vitest';
12
+ import * as gitUtils from '../../utils/gitUtils.js';
13
+ import {
14
+ setupGithubCommand,
15
+ updateGitignore,
16
+ GITHUB_WORKFLOW_PATHS,
17
+ } from './setupGithubCommand.js';
18
+ import { CommandContext, ToolActionReturn } from './types.js';
19
+ import * as commandUtils from '../utils/commandUtils.js';
20
+
21
+ vi.mock('child_process');
22
+
23
+ // Mock fetch globally
24
+ global.fetch = vi.fn();
25
+
26
+ vi.mock('../../utils/gitUtils.js', () => ({
27
+ isGitHubRepository: vi.fn(),
28
+ getGitRepoRoot: vi.fn(),
29
+ getLatestGitHubRelease: vi.fn(),
30
+ getGitHubRepoInfo: vi.fn(),
31
+ }));
32
+
33
+ vi.mock('../utils/commandUtils.js', () => ({
34
+ getUrlOpenCommand: vi.fn(),
35
+ }));
36
+
37
+ describe('setupGithubCommand', async () => {
38
+ let scratchDir = '';
39
+
40
+ beforeEach(async () => {
41
+ vi.resetAllMocks();
42
+ scratchDir = await fs.mkdtemp(
43
+ path.join(os.tmpdir(), 'setup-github-command-'),
44
+ );
45
+ });
46
+
47
+ afterEach(async () => {
48
+ vi.restoreAllMocks();
49
+ if (scratchDir) await fs.rm(scratchDir, { recursive: true });
50
+ });
51
+
52
+ it('returns a tool action to download github workflows and handles paths', async () => {
53
+ const fakeRepoOwner = 'fake';
54
+ const fakeRepoName = 'repo';
55
+ const fakeRepoRoot = scratchDir;
56
+ const fakeReleaseVersion = 'v1.2.3';
57
+
58
+ const workflows = GITHUB_WORKFLOW_PATHS.map((p) => path.basename(p));
59
+ for (const workflow of workflows) {
60
+ vi.mocked(global.fetch).mockReturnValueOnce(
61
+ Promise.resolve(new Response(workflow)),
62
+ );
63
+ }
64
+
65
+ vi.mocked(gitUtils.isGitHubRepository).mockReturnValueOnce(true);
66
+ vi.mocked(gitUtils.getGitRepoRoot).mockReturnValueOnce(fakeRepoRoot);
67
+ vi.mocked(gitUtils.getLatestGitHubRelease).mockResolvedValueOnce(
68
+ fakeReleaseVersion,
69
+ );
70
+ vi.mocked(gitUtils.getGitHubRepoInfo).mockReturnValue({
71
+ owner: fakeRepoOwner,
72
+ repo: fakeRepoName,
73
+ });
74
+ vi.mocked(commandUtils.getUrlOpenCommand).mockReturnValueOnce(
75
+ 'fakeOpenCommand',
76
+ );
77
+
78
+ const result = (await setupGithubCommand.action?.(
79
+ {} as CommandContext,
80
+ '',
81
+ )) as ToolActionReturn;
82
+
83
+ const { command } = result.toolArgs;
84
+
85
+ const expectedSubstrings = [
86
+ `set -eEuo pipefail`,
87
+ `fakeOpenCommand "https://github.com/google-github-actions/run-gemini-cli`,
88
+ ];
89
+
90
+ for (const substring of expectedSubstrings) {
91
+ expect(command).toContain(substring);
92
+ }
93
+
94
+ for (const workflow of workflows) {
95
+ const workflowFile = path.join(
96
+ scratchDir,
97
+ '.github',
98
+ 'workflows',
99
+ workflow,
100
+ );
101
+ const contents = await fs.readFile(workflowFile, 'utf8');
102
+ expect(contents).toContain(workflow);
103
+ }
104
+
105
+ // Verify that .gitignore was created with the expected entries
106
+ const gitignorePath = path.join(scratchDir, '.gitignore');
107
+ const gitignoreExists = await fs
108
+ .access(gitignorePath)
109
+ .then(() => true)
110
+ .catch(() => false);
111
+ expect(gitignoreExists).toBe(true);
112
+
113
+ if (gitignoreExists) {
114
+ const gitignoreContent = await fs.readFile(gitignorePath, 'utf8');
115
+ expect(gitignoreContent).toContain('.gemini/');
116
+ expect(gitignoreContent).toContain('gha-creds-*.json');
117
+ }
118
+ });
119
+ });
120
+
121
+ describe('updateGitignore', () => {
122
+ let scratchDir = '';
123
+
124
+ beforeEach(async () => {
125
+ scratchDir = await fs.mkdtemp(path.join(os.tmpdir(), 'update-gitignore-'));
126
+ });
127
+
128
+ afterEach(async () => {
129
+ if (scratchDir) await fs.rm(scratchDir, { recursive: true });
130
+ });
131
+
132
+ it('creates a new .gitignore file when none exists', async () => {
133
+ await updateGitignore(scratchDir);
134
+
135
+ const gitignorePath = path.join(scratchDir, '.gitignore');
136
+ const content = await fs.readFile(gitignorePath, 'utf8');
137
+
138
+ expect(content).toBe('.gemini/\ngha-creds-*.json\n');
139
+ });
140
+
141
+ it('appends entries to existing .gitignore file', async () => {
142
+ const gitignorePath = path.join(scratchDir, '.gitignore');
143
+ const existingContent = '# Existing content\nnode_modules/\n';
144
+ await fs.writeFile(gitignorePath, existingContent);
145
+
146
+ await updateGitignore(scratchDir);
147
+
148
+ const content = await fs.readFile(gitignorePath, 'utf8');
149
+
150
+ expect(content).toBe(
151
+ '# Existing content\nnode_modules/\n\n.gemini/\ngha-creds-*.json\n',
152
+ );
153
+ });
154
+
155
+ it('does not add duplicate entries', async () => {
156
+ const gitignorePath = path.join(scratchDir, '.gitignore');
157
+ const existingContent = '.gemini/\nsome-other-file\ngha-creds-*.json\n';
158
+ await fs.writeFile(gitignorePath, existingContent);
159
+
160
+ await updateGitignore(scratchDir);
161
+
162
+ const content = await fs.readFile(gitignorePath, 'utf8');
163
+
164
+ expect(content).toBe(existingContent);
165
+ });
166
+
167
+ it('adds only missing entries when some already exist', async () => {
168
+ const gitignorePath = path.join(scratchDir, '.gitignore');
169
+ const existingContent = '.gemini/\nsome-other-file\n';
170
+ await fs.writeFile(gitignorePath, existingContent);
171
+
172
+ await updateGitignore(scratchDir);
173
+
174
+ const content = await fs.readFile(gitignorePath, 'utf8');
175
+
176
+ // Should add only the missing gha-creds-*.json entry
177
+ expect(content).toBe('.gemini/\nsome-other-file\n\ngha-creds-*.json\n');
178
+ expect(content).toContain('gha-creds-*.json');
179
+ // Should not duplicate .gemini/ entry
180
+ expect((content.match(/\.gemini\//g) || []).length).toBe(1);
181
+ });
182
+
183
+ it('does not get confused by entries in comments or as substrings', async () => {
184
+ const gitignorePath = path.join(scratchDir, '.gitignore');
185
+ const existingContent = [
186
+ '# This is a comment mentioning .gemini/ folder',
187
+ 'my-app.gemini/config',
188
+ '# Another comment with gha-creds-*.json pattern',
189
+ 'some-other-gha-creds-file.json',
190
+ '',
191
+ ].join('\n');
192
+ await fs.writeFile(gitignorePath, existingContent);
193
+
194
+ await updateGitignore(scratchDir);
195
+
196
+ const content = await fs.readFile(gitignorePath, 'utf8');
197
+
198
+ // Should add both entries since they don't actually exist as gitignore rules
199
+ expect(content).toContain('.gemini/');
200
+ expect(content).toContain('gha-creds-*.json');
201
+
202
+ // Verify the entries were added (not just mentioned in comments)
203
+ const lines = content
204
+ .split('\n')
205
+ .map((line) => line.split('#')[0].trim())
206
+ .filter((line) => line);
207
+ expect(lines).toContain('.gemini/');
208
+ expect(lines).toContain('gha-creds-*.json');
209
+ expect(lines).toContain('my-app.gemini/config');
210
+ expect(lines).toContain('some-other-gha-creds-file.json');
211
+ });
212
+
213
+ it('handles file system errors gracefully', async () => {
214
+ // Try to update gitignore in a non-existent directory
215
+ const nonExistentDir = path.join(scratchDir, 'non-existent');
216
+
217
+ // This should not throw an error
218
+ await expect(updateGitignore(nonExistentDir)).resolves.toBeUndefined();
219
+ });
220
+
221
+ it('handles permission errors gracefully', async () => {
222
+ const consoleSpy = vi.spyOn(console, 'debug').mockImplementation(() => {});
223
+
224
+ const fsModule = await import('node:fs');
225
+ const writeFileSpy = vi
226
+ .spyOn(fsModule.promises, 'writeFile')
227
+ .mockRejectedValue(new Error('Permission denied'));
228
+
229
+ await expect(updateGitignore(scratchDir)).resolves.toBeUndefined();
230
+ expect(consoleSpy).toHaveBeenCalledWith(
231
+ 'Failed to update .gitignore:',
232
+ expect.any(Error),
233
+ );
234
+
235
+ writeFileSpy.mockRestore();
236
+ consoleSpy.mockRestore();
237
+ });
238
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/setupGithubCommand.ts ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import path from 'node:path';
8
+ import * as fs from 'node:fs';
9
+ import { Writable } from 'node:stream';
10
+ import { ProxyAgent } from 'undici';
11
+
12
+ import { CommandContext } from '../../ui/commands/types.js';
13
+ import {
14
+ getGitRepoRoot,
15
+ getLatestGitHubRelease,
16
+ isGitHubRepository,
17
+ getGitHubRepoInfo,
18
+ } from '../../utils/gitUtils.js';
19
+
20
+ import {
21
+ CommandKind,
22
+ SlashCommand,
23
+ SlashCommandActionReturn,
24
+ } from './types.js';
25
+ import { getUrlOpenCommand } from '../../ui/utils/commandUtils.js';
26
+
27
+ export const GITHUB_WORKFLOW_PATHS = [
28
+ 'gemini-dispatch/gemini-dispatch.yml',
29
+ 'gemini-assistant/gemini-invoke.yml',
30
+ 'issue-triage/gemini-triage.yml',
31
+ 'issue-triage/gemini-scheduled-triage.yml',
32
+ 'pr-review/gemini-review.yml',
33
+ ];
34
+
35
+ // Generate OS-specific commands to open the GitHub pages needed for setup.
36
+ function getOpenUrlsCommands(readmeUrl: string): string[] {
37
+ // Determine the OS-specific command to open URLs, ex: 'open', 'xdg-open', etc
38
+ const openCmd = getUrlOpenCommand();
39
+
40
+ // Build a list of URLs to open
41
+ const urlsToOpen = [readmeUrl];
42
+
43
+ const repoInfo = getGitHubRepoInfo();
44
+ if (repoInfo) {
45
+ urlsToOpen.push(
46
+ `https://github.com/${repoInfo.owner}/${repoInfo.repo}/settings/secrets/actions`,
47
+ );
48
+ }
49
+
50
+ // Create and join the individual commands
51
+ const commands = urlsToOpen.map((url) => `${openCmd} "${url}"`);
52
+ return commands;
53
+ }
54
+
55
+ // Add Gemini CLI specific entries to .gitignore file
56
+ export async function updateGitignore(gitRepoRoot: string): Promise<void> {
57
+ const gitignoreEntries = ['.gemini/', 'gha-creds-*.json'];
58
+
59
+ const gitignorePath = path.join(gitRepoRoot, '.gitignore');
60
+ try {
61
+ // Check if .gitignore exists and read its content
62
+ let existingContent = '';
63
+ let fileExists = true;
64
+ try {
65
+ existingContent = await fs.promises.readFile(gitignorePath, 'utf8');
66
+ } catch (_error) {
67
+ // File doesn't exist
68
+ fileExists = false;
69
+ }
70
+
71
+ if (!fileExists) {
72
+ // Create new .gitignore file with the entries
73
+ const contentToWrite = gitignoreEntries.join('\n') + '\n';
74
+ await fs.promises.writeFile(gitignorePath, contentToWrite);
75
+ } else {
76
+ // Check which entries are missing
77
+ const missingEntries = gitignoreEntries.filter(
78
+ (entry) =>
79
+ !existingContent
80
+ .split(/\r?\n/)
81
+ .some((line) => line.split('#')[0].trim() === entry),
82
+ );
83
+
84
+ if (missingEntries.length > 0) {
85
+ const contentToAdd = '\n' + missingEntries.join('\n') + '\n';
86
+ await fs.promises.appendFile(gitignorePath, contentToAdd);
87
+ }
88
+ }
89
+ } catch (error) {
90
+ console.debug('Failed to update .gitignore:', error);
91
+ // Continue without failing the whole command
92
+ }
93
+ }
94
+
95
+ export const setupGithubCommand: SlashCommand = {
96
+ name: 'setup-github',
97
+ description: 'Set up GitHub Actions',
98
+ kind: CommandKind.BUILT_IN,
99
+ action: async (
100
+ context: CommandContext,
101
+ ): Promise<SlashCommandActionReturn> => {
102
+ const abortController = new AbortController();
103
+
104
+ if (!isGitHubRepository()) {
105
+ throw new Error(
106
+ 'Unable to determine the GitHub repository. /setup-github must be run from a git repository.',
107
+ );
108
+ }
109
+
110
+ // Find the root directory of the repo
111
+ let gitRepoRoot: string;
112
+ try {
113
+ gitRepoRoot = getGitRepoRoot();
114
+ } catch (_error) {
115
+ console.debug(`Failed to get git repo root:`, _error);
116
+ throw new Error(
117
+ 'Unable to determine the GitHub repository. /setup-github must be run from a git repository.',
118
+ );
119
+ }
120
+
121
+ // Get the latest release tag from GitHub
122
+ const proxy = context?.services?.config?.getProxy();
123
+ const releaseTag = await getLatestGitHubRelease(proxy);
124
+ const readmeUrl = `https://github.com/google-github-actions/run-gemini-cli/blob/${releaseTag}/README.md#quick-start`;
125
+
126
+ // Create the .github/workflows directory to download the files into
127
+ const githubWorkflowsDir = path.join(gitRepoRoot, '.github', 'workflows');
128
+ try {
129
+ await fs.promises.mkdir(githubWorkflowsDir, { recursive: true });
130
+ } catch (_error) {
131
+ console.debug(
132
+ `Failed to create ${githubWorkflowsDir} directory:`,
133
+ _error,
134
+ );
135
+ throw new Error(
136
+ `Unable to create ${githubWorkflowsDir} directory. Do you have file permissions in the current directory?`,
137
+ );
138
+ }
139
+
140
+ // Download each workflow in parallel - there aren't enough files to warrant
141
+ // a full workerpool model here.
142
+ const downloads = [];
143
+ for (const workflow of GITHUB_WORKFLOW_PATHS) {
144
+ downloads.push(
145
+ (async () => {
146
+ const endpoint = `https://raw.githubusercontent.com/google-github-actions/run-gemini-cli/refs/tags/${releaseTag}/examples/workflows/${workflow}`;
147
+ const response = await fetch(endpoint, {
148
+ method: 'GET',
149
+ dispatcher: proxy ? new ProxyAgent(proxy) : undefined,
150
+ signal: AbortSignal.any([
151
+ AbortSignal.timeout(30_000),
152
+ abortController.signal,
153
+ ]),
154
+ } as RequestInit);
155
+
156
+ if (!response.ok) {
157
+ throw new Error(
158
+ `Invalid response code downloading ${endpoint}: ${response.status} - ${response.statusText}`,
159
+ );
160
+ }
161
+ const body = response.body;
162
+ if (!body) {
163
+ throw new Error(
164
+ `Empty body while downloading ${endpoint}: ${response.status} - ${response.statusText}`,
165
+ );
166
+ }
167
+
168
+ const destination = path.resolve(
169
+ githubWorkflowsDir,
170
+ path.basename(workflow),
171
+ );
172
+
173
+ const fileStream = fs.createWriteStream(destination, {
174
+ mode: 0o644, // -rw-r--r--, user(rw), group(r), other(r)
175
+ flags: 'w', // write and overwrite
176
+ flush: true,
177
+ });
178
+
179
+ await body.pipeTo(Writable.toWeb(fileStream));
180
+ })(),
181
+ );
182
+ }
183
+
184
+ // Wait for all downloads to complete
185
+ await Promise.all(downloads).finally(() => {
186
+ // Stop existing downloads
187
+ abortController.abort();
188
+ });
189
+
190
+ // Add entries to .gitignore file
191
+ await updateGitignore(gitRepoRoot);
192
+
193
+ // Print out a message
194
+ const commands = [];
195
+ commands.push('set -eEuo pipefail');
196
+ commands.push(
197
+ `echo "Successfully downloaded ${GITHUB_WORKFLOW_PATHS.length} workflows and updated .gitignore. Follow the steps in ${readmeUrl} (skipping the /setup-github step) to complete setup."`,
198
+ );
199
+ commands.push(...getOpenUrlsCommands(readmeUrl));
200
+
201
+ const command = `(${commands.join(' && ')})`;
202
+ return {
203
+ type: 'tool',
204
+ toolName: 'run_shell_command',
205
+ toolArgs: {
206
+ description:
207
+ 'Setting up GitHub Actions to triage issues and review PRs with Gemini.',
208
+ command,
209
+ },
210
+ };
211
+ },
212
+ };