ADAPT-Chase commited on
Commit
5d08b37
·
verified ·
1 Parent(s): cac06a2

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/core/src/utils/editor.test.ts +558 -0
  2. projects/ui/qwen-code/packages/core/src/utils/editor.ts +229 -0
  3. projects/ui/qwen-code/packages/core/src/utils/environmentContext.test.ts +215 -0
  4. projects/ui/qwen-code/packages/core/src/utils/environmentContext.ts +109 -0
  5. projects/ui/qwen-code/packages/core/src/utils/errorParsing.test.ts +375 -0
  6. projects/ui/qwen-code/packages/core/src/utils/errorParsing.ts +166 -0
  7. projects/ui/qwen-code/packages/core/src/utils/errorReporting.test.ts +193 -0
  8. projects/ui/qwen-code/packages/core/src/utils/errorReporting.ts +118 -0
  9. projects/ui/qwen-code/packages/core/src/utils/errors.ts +67 -0
  10. projects/ui/qwen-code/packages/core/src/utils/fetch.ts +57 -0
  11. projects/ui/qwen-code/packages/core/src/utils/fileUtils.test.ts +591 -0
  12. projects/ui/qwen-code/packages/core/src/utils/fileUtils.ts +378 -0
  13. projects/ui/qwen-code/packages/core/src/utils/flashFallback.integration.test.ts +153 -0
  14. projects/ui/qwen-code/packages/core/src/utils/formatters.ts +16 -0
  15. projects/ui/qwen-code/packages/core/src/utils/generateContentResponseUtilities.test.ts +323 -0
  16. projects/ui/qwen-code/packages/core/src/utils/generateContentResponseUtilities.ts +119 -0
  17. projects/ui/qwen-code/packages/core/src/utils/getFolderStructure.test.ts +340 -0
  18. projects/ui/qwen-code/packages/core/src/utils/getFolderStructure.ts +348 -0
  19. projects/ui/qwen-code/packages/core/src/utils/getPty.ts +34 -0
  20. projects/ui/qwen-code/packages/core/src/utils/gitIgnoreParser.test.ts +196 -0
projects/ui/qwen-code/packages/core/src/utils/editor.test.ts ADDED
@@ -0,0 +1,558 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ vi,
9
+ describe,
10
+ it,
11
+ expect,
12
+ beforeEach,
13
+ afterEach,
14
+ type Mock,
15
+ } from 'vitest';
16
+ import {
17
+ checkHasEditorType,
18
+ getDiffCommand,
19
+ openDiff,
20
+ allowEditorTypeInSandbox,
21
+ isEditorAvailable,
22
+ type EditorType,
23
+ } from './editor.js';
24
+ import { execSync, spawn } from 'child_process';
25
+
26
+ vi.mock('child_process', () => ({
27
+ execSync: vi.fn(),
28
+ spawn: vi.fn(),
29
+ }));
30
+
31
+ const originalPlatform = process.platform;
32
+
33
+ describe('editor utils', () => {
34
+ beforeEach(() => {
35
+ vi.clearAllMocks();
36
+ vi.unstubAllEnvs();
37
+ Object.defineProperty(process, 'platform', {
38
+ value: originalPlatform,
39
+ writable: true,
40
+ });
41
+ });
42
+
43
+ afterEach(() => {
44
+ vi.restoreAllMocks();
45
+ vi.unstubAllEnvs();
46
+ Object.defineProperty(process, 'platform', {
47
+ value: originalPlatform,
48
+ writable: true,
49
+ });
50
+ });
51
+
52
+ describe('checkHasEditorType', () => {
53
+ const testCases: Array<{
54
+ editor: EditorType;
55
+ commands: string[];
56
+ win32Commands: string[];
57
+ }> = [
58
+ { editor: 'vscode', commands: ['code'], win32Commands: ['code.cmd'] },
59
+ {
60
+ editor: 'vscodium',
61
+ commands: ['codium'],
62
+ win32Commands: ['codium.cmd'],
63
+ },
64
+ {
65
+ editor: 'windsurf',
66
+ commands: ['windsurf'],
67
+ win32Commands: ['windsurf'],
68
+ },
69
+ { editor: 'cursor', commands: ['cursor'], win32Commands: ['cursor'] },
70
+ { editor: 'vim', commands: ['vim'], win32Commands: ['vim'] },
71
+ { editor: 'neovim', commands: ['nvim'], win32Commands: ['nvim'] },
72
+ { editor: 'zed', commands: ['zed', 'zeditor'], win32Commands: ['zed'] },
73
+ { editor: 'emacs', commands: ['emacs'], win32Commands: ['emacs.exe'] },
74
+ ];
75
+
76
+ for (const { editor, commands, win32Commands } of testCases) {
77
+ describe(`${editor}`, () => {
78
+ // Non-windows tests
79
+ it(`should return true if first command "${commands[0]}" exists on non-windows`, () => {
80
+ Object.defineProperty(process, 'platform', { value: 'linux' });
81
+ (execSync as Mock).mockReturnValue(
82
+ Buffer.from(`/usr/bin/${commands[0]}`),
83
+ );
84
+ expect(checkHasEditorType(editor)).toBe(true);
85
+ expect(execSync).toHaveBeenCalledWith(`command -v ${commands[0]}`, {
86
+ stdio: 'ignore',
87
+ });
88
+ });
89
+
90
+ if (commands.length > 1) {
91
+ it(`should return true if first command doesn't exist but second command "${commands[1]}" exists on non-windows`, () => {
92
+ Object.defineProperty(process, 'platform', { value: 'linux' });
93
+ (execSync as Mock)
94
+ .mockImplementationOnce(() => {
95
+ throw new Error(); // first command not found
96
+ })
97
+ .mockReturnValueOnce(Buffer.from(`/usr/bin/${commands[1]}`)); // second command found
98
+ expect(checkHasEditorType(editor)).toBe(true);
99
+ expect(execSync).toHaveBeenCalledTimes(2);
100
+ });
101
+ }
102
+
103
+ it(`should return false if none of the commands exist on non-windows`, () => {
104
+ Object.defineProperty(process, 'platform', { value: 'linux' });
105
+ (execSync as Mock).mockImplementation(() => {
106
+ throw new Error(); // all commands not found
107
+ });
108
+ expect(checkHasEditorType(editor)).toBe(false);
109
+ expect(execSync).toHaveBeenCalledTimes(commands.length);
110
+ });
111
+
112
+ // Windows tests
113
+ it(`should return true if first command "${win32Commands[0]}" exists on windows`, () => {
114
+ Object.defineProperty(process, 'platform', { value: 'win32' });
115
+ (execSync as Mock).mockReturnValue(
116
+ Buffer.from(`C:\\Program Files\\...\\${win32Commands[0]}`),
117
+ );
118
+ expect(checkHasEditorType(editor)).toBe(true);
119
+ expect(execSync).toHaveBeenCalledWith(
120
+ `where.exe ${win32Commands[0]}`,
121
+ {
122
+ stdio: 'ignore',
123
+ },
124
+ );
125
+ });
126
+
127
+ if (win32Commands.length > 1) {
128
+ it(`should return true if first command doesn't exist but second command "${win32Commands[1]}" exists on windows`, () => {
129
+ Object.defineProperty(process, 'platform', { value: 'win32' });
130
+ (execSync as Mock)
131
+ .mockImplementationOnce(() => {
132
+ throw new Error(); // first command not found
133
+ })
134
+ .mockReturnValueOnce(
135
+ Buffer.from(`C:\\Program Files\\...\\${win32Commands[1]}`),
136
+ ); // second command found
137
+ expect(checkHasEditorType(editor)).toBe(true);
138
+ expect(execSync).toHaveBeenCalledTimes(2);
139
+ });
140
+ }
141
+
142
+ it(`should return false if none of the commands exist on windows`, () => {
143
+ Object.defineProperty(process, 'platform', { value: 'win32' });
144
+ (execSync as Mock).mockImplementation(() => {
145
+ throw new Error(); // all commands not found
146
+ });
147
+ expect(checkHasEditorType(editor)).toBe(false);
148
+ expect(execSync).toHaveBeenCalledTimes(win32Commands.length);
149
+ });
150
+ });
151
+ }
152
+ });
153
+
154
+ describe('getDiffCommand', () => {
155
+ const guiEditors: Array<{
156
+ editor: EditorType;
157
+ commands: string[];
158
+ win32Commands: string[];
159
+ }> = [
160
+ { editor: 'vscode', commands: ['code'], win32Commands: ['code.cmd'] },
161
+ {
162
+ editor: 'vscodium',
163
+ commands: ['codium'],
164
+ win32Commands: ['codium.cmd'],
165
+ },
166
+ {
167
+ editor: 'windsurf',
168
+ commands: ['windsurf'],
169
+ win32Commands: ['windsurf'],
170
+ },
171
+ { editor: 'cursor', commands: ['cursor'], win32Commands: ['cursor'] },
172
+ { editor: 'zed', commands: ['zed', 'zeditor'], win32Commands: ['zed'] },
173
+ ];
174
+
175
+ for (const { editor, commands, win32Commands } of guiEditors) {
176
+ // Non-windows tests
177
+ it(`should use first command "${commands[0]}" when it exists on non-windows`, () => {
178
+ Object.defineProperty(process, 'platform', { value: 'linux' });
179
+ (execSync as Mock).mockReturnValue(
180
+ Buffer.from(`/usr/bin/${commands[0]}`),
181
+ );
182
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor);
183
+ expect(diffCommand).toEqual({
184
+ command: commands[0],
185
+ args: ['--wait', '--diff', 'old.txt', 'new.txt'],
186
+ });
187
+ });
188
+
189
+ if (commands.length > 1) {
190
+ it(`should use second command "${commands[1]}" when first doesn't exist on non-windows`, () => {
191
+ Object.defineProperty(process, 'platform', { value: 'linux' });
192
+ (execSync as Mock)
193
+ .mockImplementationOnce(() => {
194
+ throw new Error(); // first command not found
195
+ })
196
+ .mockReturnValueOnce(Buffer.from(`/usr/bin/${commands[1]}`)); // second command found
197
+
198
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor);
199
+ expect(diffCommand).toEqual({
200
+ command: commands[1],
201
+ args: ['--wait', '--diff', 'old.txt', 'new.txt'],
202
+ });
203
+ });
204
+ }
205
+
206
+ it(`should fall back to last command "${commands[commands.length - 1]}" when none exist on non-windows`, () => {
207
+ Object.defineProperty(process, 'platform', { value: 'linux' });
208
+ (execSync as Mock).mockImplementation(() => {
209
+ throw new Error(); // all commands not found
210
+ });
211
+
212
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor);
213
+ expect(diffCommand).toEqual({
214
+ command: commands[commands.length - 1],
215
+ args: ['--wait', '--diff', 'old.txt', 'new.txt'],
216
+ });
217
+ });
218
+
219
+ // Windows tests
220
+ it(`should use first command "${win32Commands[0]}" when it exists on windows`, () => {
221
+ Object.defineProperty(process, 'platform', { value: 'win32' });
222
+ (execSync as Mock).mockReturnValue(
223
+ Buffer.from(`C:\\Program Files\\...\\${win32Commands[0]}`),
224
+ );
225
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor);
226
+ expect(diffCommand).toEqual({
227
+ command: win32Commands[0],
228
+ args: ['--wait', '--diff', 'old.txt', 'new.txt'],
229
+ });
230
+ });
231
+
232
+ if (win32Commands.length > 1) {
233
+ it(`should use second command "${win32Commands[1]}" when first doesn't exist on windows`, () => {
234
+ Object.defineProperty(process, 'platform', { value: 'win32' });
235
+ (execSync as Mock)
236
+ .mockImplementationOnce(() => {
237
+ throw new Error(); // first command not found
238
+ })
239
+ .mockReturnValueOnce(
240
+ Buffer.from(`C:\\Program Files\\...\\${win32Commands[1]}`),
241
+ ); // second command found
242
+
243
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor);
244
+ expect(diffCommand).toEqual({
245
+ command: win32Commands[1],
246
+ args: ['--wait', '--diff', 'old.txt', 'new.txt'],
247
+ });
248
+ });
249
+ }
250
+
251
+ it(`should fall back to last command "${win32Commands[win32Commands.length - 1]}" when none exist on windows`, () => {
252
+ Object.defineProperty(process, 'platform', { value: 'win32' });
253
+ (execSync as Mock).mockImplementation(() => {
254
+ throw new Error(); // all commands not found
255
+ });
256
+
257
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor);
258
+ expect(diffCommand).toEqual({
259
+ command: win32Commands[win32Commands.length - 1],
260
+ args: ['--wait', '--diff', 'old.txt', 'new.txt'],
261
+ });
262
+ });
263
+ }
264
+
265
+ const terminalEditors: Array<{
266
+ editor: EditorType;
267
+ command: string;
268
+ }> = [
269
+ { editor: 'vim', command: 'vim' },
270
+ { editor: 'neovim', command: 'nvim' },
271
+ ];
272
+
273
+ for (const { editor, command } of terminalEditors) {
274
+ it(`should return the correct command for ${editor}`, () => {
275
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor);
276
+ expect(diffCommand).toEqual({
277
+ command,
278
+ args: [
279
+ '-d',
280
+ '-i',
281
+ 'NONE',
282
+ '-c',
283
+ 'wincmd h | set readonly | wincmd l',
284
+ '-c',
285
+ 'highlight DiffAdd cterm=bold ctermbg=22 guibg=#005f00 | highlight DiffChange cterm=bold ctermbg=24 guibg=#005f87 | highlight DiffText ctermbg=21 guibg=#0000af | highlight DiffDelete ctermbg=52 guibg=#5f0000',
286
+ '-c',
287
+ 'set showtabline=2 | set tabline=[Instructions]\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)',
288
+ '-c',
289
+ 'wincmd h | setlocal statusline=OLD\\ FILE',
290
+ '-c',
291
+ 'wincmd l | setlocal statusline=%#StatusBold#NEW\\ FILE\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)',
292
+ '-c',
293
+ 'autocmd WinClosed * wqa',
294
+ 'old.txt',
295
+ 'new.txt',
296
+ ],
297
+ });
298
+ });
299
+ }
300
+
301
+ it('should return the correct command for emacs', () => {
302
+ const command = getDiffCommand('old.txt', 'new.txt', 'emacs');
303
+ expect(command).toEqual({
304
+ command: 'emacs',
305
+ args: ['--eval', '(ediff "old.txt" "new.txt")'],
306
+ });
307
+ });
308
+
309
+ it('should return null for an unsupported editor', () => {
310
+ // @ts-expect-error Testing unsupported editor
311
+ const command = getDiffCommand('old.txt', 'new.txt', 'foobar');
312
+ expect(command).toBeNull();
313
+ });
314
+ });
315
+
316
+ describe('openDiff', () => {
317
+ const spawnEditors: EditorType[] = [
318
+ 'vscode',
319
+ 'vscodium',
320
+ 'windsurf',
321
+ 'cursor',
322
+ 'zed',
323
+ ];
324
+ for (const editor of spawnEditors) {
325
+ it(`should call spawn for ${editor}`, async () => {
326
+ const mockSpawn = {
327
+ on: vi.fn((event, cb) => {
328
+ if (event === 'close') {
329
+ cb(0);
330
+ }
331
+ }),
332
+ };
333
+ (spawn as Mock).mockReturnValue(mockSpawn);
334
+ await openDiff('old.txt', 'new.txt', editor, () => {});
335
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor)!;
336
+ expect(spawn).toHaveBeenCalledWith(
337
+ diffCommand.command,
338
+ diffCommand.args,
339
+ {
340
+ stdio: 'inherit',
341
+ shell: true,
342
+ },
343
+ );
344
+ expect(mockSpawn.on).toHaveBeenCalledWith(
345
+ 'close',
346
+ expect.any(Function),
347
+ );
348
+ expect(mockSpawn.on).toHaveBeenCalledWith(
349
+ 'error',
350
+ expect.any(Function),
351
+ );
352
+ });
353
+
354
+ it(`should reject if spawn for ${editor} fails`, async () => {
355
+ const mockError = new Error('spawn error');
356
+ const mockSpawn = {
357
+ on: vi.fn((event, cb) => {
358
+ if (event === 'error') {
359
+ cb(mockError);
360
+ }
361
+ }),
362
+ };
363
+ (spawn as Mock).mockReturnValue(mockSpawn);
364
+ await expect(
365
+ openDiff('old.txt', 'new.txt', editor, () => {}),
366
+ ).rejects.toThrow('spawn error');
367
+ });
368
+
369
+ it(`should reject if ${editor} exits with non-zero code`, async () => {
370
+ const mockSpawn = {
371
+ on: vi.fn((event, cb) => {
372
+ if (event === 'close') {
373
+ cb(1);
374
+ }
375
+ }),
376
+ };
377
+ (spawn as Mock).mockReturnValue(mockSpawn);
378
+ await expect(
379
+ openDiff('old.txt', 'new.txt', editor, () => {}),
380
+ ).rejects.toThrow(`${editor} exited with code 1`);
381
+ });
382
+ }
383
+
384
+ const execSyncEditors: EditorType[] = ['vim', 'neovim', 'emacs'];
385
+ for (const editor of execSyncEditors) {
386
+ it(`should call execSync for ${editor} on non-windows`, async () => {
387
+ Object.defineProperty(process, 'platform', { value: 'linux' });
388
+ await openDiff('old.txt', 'new.txt', editor, () => {});
389
+ expect(execSync).toHaveBeenCalledTimes(1);
390
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor)!;
391
+ const expectedCommand = `${
392
+ diffCommand.command
393
+ } ${diffCommand.args.map((arg) => `"${arg}"`).join(' ')}`;
394
+ expect(execSync).toHaveBeenCalledWith(expectedCommand, {
395
+ stdio: 'inherit',
396
+ encoding: 'utf8',
397
+ });
398
+ });
399
+
400
+ it(`should call execSync for ${editor} on windows`, async () => {
401
+ Object.defineProperty(process, 'platform', { value: 'win32' });
402
+ await openDiff('old.txt', 'new.txt', editor, () => {});
403
+ expect(execSync).toHaveBeenCalledTimes(1);
404
+ const diffCommand = getDiffCommand('old.txt', 'new.txt', editor)!;
405
+ const expectedCommand = `${diffCommand.command} ${diffCommand.args.join(
406
+ ' ',
407
+ )}`;
408
+ expect(execSync).toHaveBeenCalledWith(expectedCommand, {
409
+ stdio: 'inherit',
410
+ encoding: 'utf8',
411
+ });
412
+ });
413
+ }
414
+
415
+ it('should log an error if diff command is not available', async () => {
416
+ const consoleErrorSpy = vi
417
+ .spyOn(console, 'error')
418
+ .mockImplementation(() => {});
419
+ // @ts-expect-error Testing unsupported editor
420
+ await openDiff('old.txt', 'new.txt', 'foobar', () => {});
421
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
422
+ 'No diff tool available. Install a supported editor.',
423
+ );
424
+ });
425
+
426
+ describe('onEditorClose callback', () => {
427
+ it('should call onEditorClose for execSync editors', async () => {
428
+ (execSync as Mock).mockReturnValue(Buffer.from(`/usr/bin/`));
429
+ const onEditorClose = vi.fn();
430
+ await openDiff('old.txt', 'new.txt', 'vim', onEditorClose);
431
+ expect(execSync).toHaveBeenCalledTimes(1);
432
+ expect(onEditorClose).toHaveBeenCalledTimes(1);
433
+ });
434
+
435
+ it('should call onEditorClose for execSync editors when an error is thrown', async () => {
436
+ (execSync as Mock).mockImplementation(() => {
437
+ throw new Error('test error');
438
+ });
439
+ const onEditorClose = vi.fn();
440
+ openDiff('old.txt', 'new.txt', 'vim', onEditorClose);
441
+ expect(execSync).toHaveBeenCalledTimes(1);
442
+ expect(onEditorClose).toHaveBeenCalledTimes(1);
443
+ });
444
+
445
+ it('should not call onEditorClose for spawn editors', async () => {
446
+ const onEditorClose = vi.fn();
447
+ const mockSpawn = {
448
+ on: vi.fn((event, cb) => {
449
+ if (event === 'close') {
450
+ cb(0);
451
+ }
452
+ }),
453
+ };
454
+ (spawn as Mock).mockReturnValue(mockSpawn);
455
+ await openDiff('old.txt', 'new.txt', 'vscode', onEditorClose);
456
+ expect(spawn).toHaveBeenCalledTimes(1);
457
+ expect(onEditorClose).not.toHaveBeenCalled();
458
+ });
459
+ });
460
+ });
461
+
462
+ describe('allowEditorTypeInSandbox', () => {
463
+ it('should allow vim in sandbox mode', () => {
464
+ vi.stubEnv('SANDBOX', 'sandbox');
465
+ expect(allowEditorTypeInSandbox('vim')).toBe(true);
466
+ });
467
+
468
+ it('should allow vim when not in sandbox mode', () => {
469
+ expect(allowEditorTypeInSandbox('vim')).toBe(true);
470
+ });
471
+
472
+ it('should allow emacs in sandbox mode', () => {
473
+ vi.stubEnv('SANDBOX', 'sandbox');
474
+ expect(allowEditorTypeInSandbox('emacs')).toBe(true);
475
+ });
476
+
477
+ it('should allow emacs when not in sandbox mode', () => {
478
+ expect(allowEditorTypeInSandbox('emacs')).toBe(true);
479
+ });
480
+
481
+ it('should allow neovim in sandbox mode', () => {
482
+ vi.stubEnv('SANDBOX', 'sandbox');
483
+ expect(allowEditorTypeInSandbox('neovim')).toBe(true);
484
+ });
485
+
486
+ it('should allow neovim when not in sandbox mode', () => {
487
+ expect(allowEditorTypeInSandbox('neovim')).toBe(true);
488
+ });
489
+
490
+ const guiEditors: EditorType[] = [
491
+ 'vscode',
492
+ 'vscodium',
493
+ 'windsurf',
494
+ 'cursor',
495
+ 'zed',
496
+ ];
497
+ for (const editor of guiEditors) {
498
+ it(`should not allow ${editor} in sandbox mode`, () => {
499
+ vi.stubEnv('SANDBOX', 'sandbox');
500
+ expect(allowEditorTypeInSandbox(editor)).toBe(false);
501
+ });
502
+
503
+ it(`should allow ${editor} when not in sandbox mode`, () => {
504
+ expect(allowEditorTypeInSandbox(editor)).toBe(true);
505
+ });
506
+ }
507
+ });
508
+
509
+ describe('isEditorAvailable', () => {
510
+ it('should return false for undefined editor', () => {
511
+ expect(isEditorAvailable(undefined)).toBe(false);
512
+ });
513
+
514
+ it('should return false for empty string editor', () => {
515
+ expect(isEditorAvailable('')).toBe(false);
516
+ });
517
+
518
+ it('should return false for invalid editor type', () => {
519
+ expect(isEditorAvailable('invalid-editor')).toBe(false);
520
+ });
521
+
522
+ it('should return true for vscode when installed and not in sandbox mode', () => {
523
+ (execSync as Mock).mockReturnValue(Buffer.from('/usr/bin/code'));
524
+ expect(isEditorAvailable('vscode')).toBe(true);
525
+ });
526
+
527
+ it('should return false for vscode when not installed and not in sandbox mode', () => {
528
+ (execSync as Mock).mockImplementation(() => {
529
+ throw new Error();
530
+ });
531
+ expect(isEditorAvailable('vscode')).toBe(false);
532
+ });
533
+
534
+ it('should return false for vscode when installed and in sandbox mode', () => {
535
+ (execSync as Mock).mockReturnValue(Buffer.from('/usr/bin/code'));
536
+ vi.stubEnv('SANDBOX', 'sandbox');
537
+ expect(isEditorAvailable('vscode')).toBe(false);
538
+ });
539
+
540
+ it('should return true for vim when installed and in sandbox mode', () => {
541
+ (execSync as Mock).mockReturnValue(Buffer.from('/usr/bin/vim'));
542
+ vi.stubEnv('SANDBOX', 'sandbox');
543
+ expect(isEditorAvailable('vim')).toBe(true);
544
+ });
545
+
546
+ it('should return true for emacs when installed and in sandbox mode', () => {
547
+ (execSync as Mock).mockReturnValue(Buffer.from('/usr/bin/emacs'));
548
+ vi.stubEnv('SANDBOX', 'sandbox');
549
+ expect(isEditorAvailable('emacs')).toBe(true);
550
+ });
551
+
552
+ it('should return true for neovim when installed and in sandbox mode', () => {
553
+ (execSync as Mock).mockReturnValue(Buffer.from('/usr/bin/nvim'));
554
+ vi.stubEnv('SANDBOX', 'sandbox');
555
+ expect(isEditorAvailable('neovim')).toBe(true);
556
+ });
557
+ });
558
+ });
projects/ui/qwen-code/packages/core/src/utils/editor.ts ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { execSync, spawn } from 'child_process';
8
+
9
+ export type EditorType =
10
+ | 'vscode'
11
+ | 'vscodium'
12
+ | 'windsurf'
13
+ | 'cursor'
14
+ | 'vim'
15
+ | 'neovim'
16
+ | 'zed'
17
+ | 'emacs';
18
+
19
+ function isValidEditorType(editor: string): editor is EditorType {
20
+ return [
21
+ 'vscode',
22
+ 'vscodium',
23
+ 'windsurf',
24
+ 'cursor',
25
+ 'vim',
26
+ 'neovim',
27
+ 'zed',
28
+ 'emacs',
29
+ ].includes(editor);
30
+ }
31
+
32
+ interface DiffCommand {
33
+ command: string;
34
+ args: string[];
35
+ }
36
+
37
+ function commandExists(cmd: string): boolean {
38
+ try {
39
+ execSync(
40
+ process.platform === 'win32' ? `where.exe ${cmd}` : `command -v ${cmd}`,
41
+ { stdio: 'ignore' },
42
+ );
43
+ return true;
44
+ } catch {
45
+ return false;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Editor command configurations for different platforms.
51
+ * Each editor can have multiple possible command names, listed in order of preference.
52
+ */
53
+ const editorCommands: Record<
54
+ EditorType,
55
+ { win32: string[]; default: string[] }
56
+ > = {
57
+ vscode: { win32: ['code.cmd'], default: ['code'] },
58
+ vscodium: { win32: ['codium.cmd'], default: ['codium'] },
59
+ windsurf: { win32: ['windsurf'], default: ['windsurf'] },
60
+ cursor: { win32: ['cursor'], default: ['cursor'] },
61
+ vim: { win32: ['vim'], default: ['vim'] },
62
+ neovim: { win32: ['nvim'], default: ['nvim'] },
63
+ zed: { win32: ['zed'], default: ['zed', 'zeditor'] },
64
+ emacs: { win32: ['emacs.exe'], default: ['emacs'] },
65
+ };
66
+
67
+ export function checkHasEditorType(editor: EditorType): boolean {
68
+ const commandConfig = editorCommands[editor];
69
+ const commands =
70
+ process.platform === 'win32' ? commandConfig.win32 : commandConfig.default;
71
+ return commands.some((cmd) => commandExists(cmd));
72
+ }
73
+
74
+ export function allowEditorTypeInSandbox(editor: EditorType): boolean {
75
+ const notUsingSandbox = !process.env['SANDBOX'];
76
+ if (['vscode', 'vscodium', 'windsurf', 'cursor', 'zed'].includes(editor)) {
77
+ return notUsingSandbox;
78
+ }
79
+ // For terminal-based editors like vim and emacs, allow in sandbox.
80
+ return true;
81
+ }
82
+
83
+ /**
84
+ * Check if the editor is valid and can be used.
85
+ * Returns false if preferred editor is not set / invalid / not available / not allowed in sandbox.
86
+ */
87
+ export function isEditorAvailable(editor: string | undefined): boolean {
88
+ if (editor && isValidEditorType(editor)) {
89
+ return checkHasEditorType(editor) && allowEditorTypeInSandbox(editor);
90
+ }
91
+ return false;
92
+ }
93
+
94
+ /**
95
+ * Get the diff command for a specific editor.
96
+ */
97
+ export function getDiffCommand(
98
+ oldPath: string,
99
+ newPath: string,
100
+ editor: EditorType,
101
+ ): DiffCommand | null {
102
+ if (!isValidEditorType(editor)) {
103
+ return null;
104
+ }
105
+ const commandConfig = editorCommands[editor];
106
+ const commands =
107
+ process.platform === 'win32' ? commandConfig.win32 : commandConfig.default;
108
+ const command =
109
+ commands.slice(0, -1).find((cmd) => commandExists(cmd)) ||
110
+ commands[commands.length - 1];
111
+
112
+ switch (editor) {
113
+ case 'vscode':
114
+ case 'vscodium':
115
+ case 'windsurf':
116
+ case 'cursor':
117
+ case 'zed':
118
+ return { command, args: ['--wait', '--diff', oldPath, newPath] };
119
+ case 'vim':
120
+ case 'neovim':
121
+ return {
122
+ command,
123
+ args: [
124
+ '-d',
125
+ // skip viminfo file to avoid E138 errors
126
+ '-i',
127
+ 'NONE',
128
+ // make the left window read-only and the right window editable
129
+ '-c',
130
+ 'wincmd h | set readonly | wincmd l',
131
+ // set up colors for diffs
132
+ '-c',
133
+ 'highlight DiffAdd cterm=bold ctermbg=22 guibg=#005f00 | highlight DiffChange cterm=bold ctermbg=24 guibg=#005f87 | highlight DiffText ctermbg=21 guibg=#0000af | highlight DiffDelete ctermbg=52 guibg=#5f0000',
134
+ // Show helpful messages
135
+ '-c',
136
+ 'set showtabline=2 | set tabline=[Instructions]\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)',
137
+ '-c',
138
+ 'wincmd h | setlocal statusline=OLD\\ FILE',
139
+ '-c',
140
+ 'wincmd l | setlocal statusline=%#StatusBold#NEW\\ FILE\\ :wqa(save\\ &\\ quit)\\ \\|\\ i/esc(toggle\\ edit\\ mode)',
141
+ // Auto close all windows when one is closed
142
+ '-c',
143
+ 'autocmd WinClosed * wqa',
144
+ oldPath,
145
+ newPath,
146
+ ],
147
+ };
148
+ case 'emacs':
149
+ return {
150
+ command: 'emacs',
151
+ args: ['--eval', `(ediff "${oldPath}" "${newPath}")`],
152
+ };
153
+ default:
154
+ return null;
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Opens a diff tool to compare two files.
160
+ * Terminal-based editors by default blocks parent process until the editor exits.
161
+ * GUI-based editors require args such as "--wait" to block parent process.
162
+ */
163
+ export async function openDiff(
164
+ oldPath: string,
165
+ newPath: string,
166
+ editor: EditorType,
167
+ onEditorClose: () => void,
168
+ ): Promise<void> {
169
+ const diffCommand = getDiffCommand(oldPath, newPath, editor);
170
+ if (!diffCommand) {
171
+ console.error('No diff tool available. Install a supported editor.');
172
+ return;
173
+ }
174
+
175
+ try {
176
+ switch (editor) {
177
+ case 'vscode':
178
+ case 'vscodium':
179
+ case 'windsurf':
180
+ case 'cursor':
181
+ case 'zed':
182
+ // Use spawn for GUI-based editors to avoid blocking the entire process
183
+ return new Promise((resolve, reject) => {
184
+ const childProcess = spawn(diffCommand.command, diffCommand.args, {
185
+ stdio: 'inherit',
186
+ shell: true,
187
+ });
188
+
189
+ childProcess.on('close', (code) => {
190
+ if (code === 0) {
191
+ resolve();
192
+ } else {
193
+ reject(new Error(`${editor} exited with code ${code}`));
194
+ }
195
+ });
196
+
197
+ childProcess.on('error', (error) => {
198
+ reject(error);
199
+ });
200
+ });
201
+
202
+ case 'vim':
203
+ case 'emacs':
204
+ case 'neovim': {
205
+ // Use execSync for terminal-based editors
206
+ const command =
207
+ process.platform === 'win32'
208
+ ? `${diffCommand.command} ${diffCommand.args.join(' ')}`
209
+ : `${diffCommand.command} ${diffCommand.args.map((arg) => `"${arg}"`).join(' ')}`;
210
+ try {
211
+ execSync(command, {
212
+ stdio: 'inherit',
213
+ encoding: 'utf8',
214
+ });
215
+ } catch (e) {
216
+ console.error('Error in onEditorClose callback:', e);
217
+ } finally {
218
+ onEditorClose();
219
+ }
220
+ break;
221
+ }
222
+
223
+ default:
224
+ throw new Error(`Unsupported editor: ${editor}`);
225
+ }
226
+ } catch (error) {
227
+ console.error(error);
228
+ }
229
+ }
projects/ui/qwen-code/packages/core/src/utils/environmentContext.test.ts ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ describe,
9
+ it,
10
+ expect,
11
+ vi,
12
+ beforeEach,
13
+ afterEach,
14
+ type Mock,
15
+ } from 'vitest';
16
+ import {
17
+ getEnvironmentContext,
18
+ getDirectoryContextString,
19
+ } from './environmentContext.js';
20
+ import { Config } from '../config/config.js';
21
+ import { getFolderStructure } from './getFolderStructure.js';
22
+
23
+ vi.mock('../config/config.js');
24
+ vi.mock('./getFolderStructure.js', () => ({
25
+ getFolderStructure: vi.fn(),
26
+ }));
27
+ vi.mock('../tools/read-many-files.js');
28
+
29
+ describe('getDirectoryContextString', () => {
30
+ let mockConfig: Partial<Config>;
31
+
32
+ beforeEach(() => {
33
+ mockConfig = {
34
+ getWorkspaceContext: vi.fn().mockReturnValue({
35
+ getDirectories: vi.fn().mockReturnValue(['/test/dir']),
36
+ }),
37
+ getFileService: vi.fn(),
38
+ };
39
+ vi.mocked(getFolderStructure).mockResolvedValue('Mock Folder Structure');
40
+ });
41
+
42
+ afterEach(() => {
43
+ vi.resetAllMocks();
44
+ });
45
+
46
+ it('should return context string for a single directory', async () => {
47
+ const contextString = await getDirectoryContextString(mockConfig as Config);
48
+ expect(contextString).toContain(
49
+ "I'm currently working in the directory: /test/dir",
50
+ );
51
+ expect(contextString).toContain(
52
+ 'Here is the folder structure of the current working directories:\n\nMock Folder Structure',
53
+ );
54
+ });
55
+
56
+ it('should return context string for multiple directories', async () => {
57
+ (
58
+ vi.mocked(mockConfig.getWorkspaceContext!)().getDirectories as Mock
59
+ ).mockReturnValue(['/test/dir1', '/test/dir2']);
60
+ vi.mocked(getFolderStructure)
61
+ .mockResolvedValueOnce('Structure 1')
62
+ .mockResolvedValueOnce('Structure 2');
63
+
64
+ const contextString = await getDirectoryContextString(mockConfig as Config);
65
+ expect(contextString).toContain(
66
+ "I'm currently working in the following directories:\n - /test/dir1\n - /test/dir2",
67
+ );
68
+ expect(contextString).toContain(
69
+ 'Here is the folder structure of the current working directories:\n\nStructure 1\nStructure 2',
70
+ );
71
+ });
72
+ });
73
+
74
+ describe('getEnvironmentContext', () => {
75
+ let mockConfig: Partial<Config>;
76
+ let mockToolRegistry: { getTool: Mock };
77
+
78
+ beforeEach(() => {
79
+ vi.useFakeTimers();
80
+ vi.setSystemTime(new Date('2025-08-05T12:00:00Z'));
81
+
82
+ // Mock the locale to ensure consistent English date formatting
83
+ vi.stubGlobal('Intl', {
84
+ ...global.Intl,
85
+ DateTimeFormat: vi.fn().mockImplementation(() => ({
86
+ format: vi.fn().mockReturnValue('Tuesday, August 5, 2025'),
87
+ })),
88
+ });
89
+
90
+ mockToolRegistry = {
91
+ getTool: vi.fn(),
92
+ };
93
+
94
+ mockConfig = {
95
+ getWorkspaceContext: vi.fn().mockReturnValue({
96
+ getDirectories: vi.fn().mockReturnValue(['/test/dir']),
97
+ }),
98
+ getFileService: vi.fn(),
99
+ getFullContext: vi.fn().mockReturnValue(false),
100
+ getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
101
+ };
102
+
103
+ vi.mocked(getFolderStructure).mockResolvedValue('Mock Folder Structure');
104
+ });
105
+
106
+ afterEach(() => {
107
+ vi.useRealTimers();
108
+ vi.unstubAllGlobals();
109
+ vi.resetAllMocks();
110
+ });
111
+
112
+ it('should return basic environment context for a single directory', async () => {
113
+ const parts = await getEnvironmentContext(mockConfig as Config);
114
+
115
+ expect(parts.length).toBe(1);
116
+ const context = parts[0].text;
117
+
118
+ expect(context).toContain("Today's date is");
119
+ expect(context).toContain("(formatted according to the user's locale)");
120
+ expect(context).toContain(`My operating system is: ${process.platform}`);
121
+ expect(context).toContain(
122
+ "I'm currently working in the directory: /test/dir",
123
+ );
124
+ expect(context).toContain(
125
+ 'Here is the folder structure of the current working directories:\n\nMock Folder Structure',
126
+ );
127
+ expect(getFolderStructure).toHaveBeenCalledWith('/test/dir', {
128
+ fileService: undefined,
129
+ });
130
+ });
131
+
132
+ it('should return basic environment context for multiple directories', async () => {
133
+ (
134
+ vi.mocked(mockConfig.getWorkspaceContext!)().getDirectories as Mock
135
+ ).mockReturnValue(['/test/dir1', '/test/dir2']);
136
+ vi.mocked(getFolderStructure)
137
+ .mockResolvedValueOnce('Structure 1')
138
+ .mockResolvedValueOnce('Structure 2');
139
+
140
+ const parts = await getEnvironmentContext(mockConfig as Config);
141
+
142
+ expect(parts.length).toBe(1);
143
+ const context = parts[0].text;
144
+
145
+ expect(context).toContain(
146
+ "I'm currently working in the following directories:\n - /test/dir1\n - /test/dir2",
147
+ );
148
+ expect(context).toContain(
149
+ 'Here is the folder structure of the current working directories:\n\nStructure 1\nStructure 2',
150
+ );
151
+ expect(getFolderStructure).toHaveBeenCalledTimes(2);
152
+ });
153
+
154
+ it('should include full file context when getFullContext is true', async () => {
155
+ mockConfig.getFullContext = vi.fn().mockReturnValue(true);
156
+ const mockReadManyFilesTool = {
157
+ build: vi.fn().mockReturnValue({
158
+ execute: vi
159
+ .fn()
160
+ .mockResolvedValue({ llmContent: 'Full file content here' }),
161
+ }),
162
+ };
163
+ mockToolRegistry.getTool.mockReturnValue(mockReadManyFilesTool);
164
+
165
+ const parts = await getEnvironmentContext(mockConfig as Config);
166
+
167
+ expect(parts.length).toBe(2);
168
+ expect(parts[1].text).toBe(
169
+ '\n--- Full File Context ---\nFull file content here',
170
+ );
171
+ expect(mockToolRegistry.getTool).toHaveBeenCalledWith('read_many_files');
172
+ expect(mockReadManyFilesTool.build).toHaveBeenCalledWith({
173
+ paths: ['**/*'],
174
+ useDefaultExcludes: true,
175
+ });
176
+ });
177
+
178
+ it('should handle read_many_files returning no content', async () => {
179
+ mockConfig.getFullContext = vi.fn().mockReturnValue(true);
180
+ const mockReadManyFilesTool = {
181
+ build: vi.fn().mockReturnValue({
182
+ execute: vi.fn().mockResolvedValue({ llmContent: '' }),
183
+ }),
184
+ };
185
+ mockToolRegistry.getTool.mockReturnValue(mockReadManyFilesTool);
186
+
187
+ const parts = await getEnvironmentContext(mockConfig as Config);
188
+
189
+ expect(parts.length).toBe(1); // No extra part added
190
+ });
191
+
192
+ it('should handle read_many_files tool not being found', async () => {
193
+ mockConfig.getFullContext = vi.fn().mockReturnValue(true);
194
+ mockToolRegistry.getTool.mockReturnValue(null);
195
+
196
+ const parts = await getEnvironmentContext(mockConfig as Config);
197
+
198
+ expect(parts.length).toBe(1); // No extra part added
199
+ });
200
+
201
+ it('should handle errors when reading full file context', async () => {
202
+ mockConfig.getFullContext = vi.fn().mockReturnValue(true);
203
+ const mockReadManyFilesTool = {
204
+ build: vi.fn().mockReturnValue({
205
+ execute: vi.fn().mockRejectedValue(new Error('Read error')),
206
+ }),
207
+ };
208
+ mockToolRegistry.getTool.mockReturnValue(mockReadManyFilesTool);
209
+
210
+ const parts = await getEnvironmentContext(mockConfig as Config);
211
+
212
+ expect(parts.length).toBe(2);
213
+ expect(parts[1].text).toBe('\n--- Error reading full file context ---');
214
+ });
215
+ });
projects/ui/qwen-code/packages/core/src/utils/environmentContext.ts ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Part } from '@google/genai';
8
+ import { Config } from '../config/config.js';
9
+ import { getFolderStructure } from './getFolderStructure.js';
10
+
11
+ /**
12
+ * Generates a string describing the current workspace directories and their structures.
13
+ * @param {Config} config - The runtime configuration and services.
14
+ * @returns {Promise<string>} A promise that resolves to the directory context string.
15
+ */
16
+ export async function getDirectoryContextString(
17
+ config: Config,
18
+ ): Promise<string> {
19
+ const workspaceContext = config.getWorkspaceContext();
20
+ const workspaceDirectories = workspaceContext.getDirectories();
21
+
22
+ const folderStructures = await Promise.all(
23
+ workspaceDirectories.map((dir) =>
24
+ getFolderStructure(dir, {
25
+ fileService: config.getFileService(),
26
+ }),
27
+ ),
28
+ );
29
+
30
+ const folderStructure = folderStructures.join('\n');
31
+
32
+ let workingDirPreamble: string;
33
+ if (workspaceDirectories.length === 1) {
34
+ workingDirPreamble = `I'm currently working in the directory: ${workspaceDirectories[0]}`;
35
+ } else {
36
+ const dirList = workspaceDirectories.map((dir) => ` - ${dir}`).join('\n');
37
+ workingDirPreamble = `I'm currently working in the following directories:\n${dirList}`;
38
+ }
39
+
40
+ return `${workingDirPreamble}
41
+ Here is the folder structure of the current working directories:
42
+
43
+ ${folderStructure}`;
44
+ }
45
+
46
+ /**
47
+ * Retrieves environment-related information to be included in the chat context.
48
+ * This includes the current working directory, date, operating system, and folder structure.
49
+ * Optionally, it can also include the full file context if enabled.
50
+ * @param {Config} config - The runtime configuration and services.
51
+ * @returns A promise that resolves to an array of `Part` objects containing environment information.
52
+ */
53
+ export async function getEnvironmentContext(config: Config): Promise<Part[]> {
54
+ const today = new Date().toLocaleDateString(undefined, {
55
+ weekday: 'long',
56
+ year: 'numeric',
57
+ month: 'long',
58
+ day: 'numeric',
59
+ });
60
+ const platform = process.platform;
61
+ const directoryContext = await getDirectoryContextString(config);
62
+
63
+ const context = `
64
+ This is the Qwen Code. We are setting up the context for our chat.
65
+ Today's date is ${today} (formatted according to the user's locale).
66
+ My operating system is: ${platform}
67
+ ${directoryContext}
68
+ `.trim();
69
+
70
+ const initialParts: Part[] = [{ text: context }];
71
+ const toolRegistry = config.getToolRegistry();
72
+
73
+ // Add full file context if the flag is set
74
+ if (config.getFullContext()) {
75
+ try {
76
+ const readManyFilesTool = toolRegistry.getTool('read_many_files');
77
+ if (readManyFilesTool) {
78
+ const invocation = readManyFilesTool.build({
79
+ paths: ['**/*'], // Read everything recursively
80
+ useDefaultExcludes: true, // Use default excludes
81
+ });
82
+
83
+ // Read all files in the target directory
84
+ const result = await invocation.execute(AbortSignal.timeout(30000));
85
+ if (result.llmContent) {
86
+ initialParts.push({
87
+ text: `\n--- Full File Context ---\n${result.llmContent}`,
88
+ });
89
+ } else {
90
+ console.warn(
91
+ 'Full context requested, but read_many_files returned no content.',
92
+ );
93
+ }
94
+ } else {
95
+ console.warn(
96
+ 'Full context requested, but read_many_files tool not found.',
97
+ );
98
+ }
99
+ } catch (error) {
100
+ // Not using reportError here as it's a startup/config phase, not a chat/generation phase error.
101
+ console.error('Error reading full file context:', error);
102
+ initialParts.push({
103
+ text: '\n--- Error reading full file context ---',
104
+ });
105
+ }
106
+ }
107
+
108
+ return initialParts;
109
+ }
projects/ui/qwen-code/packages/core/src/utils/errorParsing.test.ts ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import { parseAndFormatApiError } from './errorParsing.js';
9
+ import { isProQuotaExceededError } from './quotaErrorDetection.js';
10
+ import { DEFAULT_GEMINI_FLASH_MODEL } from '../config/models.js';
11
+ import { UserTierId } from '../code_assist/types.js';
12
+ import { AuthType } from '../core/contentGenerator.js';
13
+ import { StructuredError } from '../core/turn.js';
14
+
15
+ describe('parseAndFormatApiError', () => {
16
+ const vertexMessage = 'request a quota increase through Vertex';
17
+ const geminiMessage = 'request a quota increase through AI Studio';
18
+
19
+ it('should format a valid API error JSON', () => {
20
+ const errorMessage =
21
+ 'got status: 400 Bad Request. {"error":{"code":400,"message":"API key not valid. Please pass a valid API key.","status":"INVALID_ARGUMENT"}}';
22
+ const expected =
23
+ '[API Error: API key not valid. Please pass a valid API key. (Status: INVALID_ARGUMENT)]';
24
+ expect(parseAndFormatApiError(errorMessage)).toBe(expected);
25
+ });
26
+
27
+ it('should format a 429 API error with the default message', () => {
28
+ const errorMessage =
29
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Rate limit exceeded","status":"RESOURCE_EXHAUSTED"}}';
30
+ const result = parseAndFormatApiError(
31
+ errorMessage,
32
+ undefined,
33
+ undefined,
34
+ 'gemini-2.5-pro',
35
+ DEFAULT_GEMINI_FLASH_MODEL,
36
+ );
37
+ expect(result).toContain('[API Error: Rate limit exceeded');
38
+ expect(result).toContain(
39
+ 'Possible quota limitations in place or slow response times detected. Switching to the gemini-2.5-flash model',
40
+ );
41
+ });
42
+
43
+ it('should format a 429 API error with the personal message', () => {
44
+ const errorMessage =
45
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Rate limit exceeded","status":"RESOURCE_EXHAUSTED"}}';
46
+ const result = parseAndFormatApiError(
47
+ errorMessage,
48
+ AuthType.LOGIN_WITH_GOOGLE,
49
+ undefined,
50
+ 'gemini-2.5-pro',
51
+ DEFAULT_GEMINI_FLASH_MODEL,
52
+ );
53
+ expect(result).toContain('[API Error: Rate limit exceeded');
54
+ expect(result).toContain(
55
+ 'Possible quota limitations in place or slow response times detected. Switching to the gemini-2.5-flash model',
56
+ );
57
+ });
58
+
59
+ it('should format a 429 API error with the vertex message', () => {
60
+ const errorMessage =
61
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Rate limit exceeded","status":"RESOURCE_EXHAUSTED"}}';
62
+ const result = parseAndFormatApiError(errorMessage, AuthType.USE_VERTEX_AI);
63
+ expect(result).toContain('[API Error: Rate limit exceeded');
64
+ expect(result).toContain(vertexMessage);
65
+ });
66
+
67
+ it('should return the original message if it is not a JSON error', () => {
68
+ const errorMessage = 'This is a plain old error message';
69
+ expect(parseAndFormatApiError(errorMessage)).toBe(
70
+ `[API Error: ${errorMessage}]`,
71
+ );
72
+ });
73
+
74
+ it('should return the original message for malformed JSON', () => {
75
+ const errorMessage = '[Stream Error: {"error": "malformed}';
76
+ expect(parseAndFormatApiError(errorMessage)).toBe(
77
+ `[API Error: ${errorMessage}]`,
78
+ );
79
+ });
80
+
81
+ it('should handle JSON that does not match the ApiError structure', () => {
82
+ const errorMessage = '[Stream Error: {"not_an_error": "some other json"}]';
83
+ expect(parseAndFormatApiError(errorMessage)).toBe(
84
+ `[API Error: ${errorMessage}]`,
85
+ );
86
+ });
87
+
88
+ it('should format a nested API error', () => {
89
+ const nestedErrorMessage = JSON.stringify({
90
+ error: {
91
+ code: 429,
92
+ message:
93
+ "Gemini 2.5 Pro Preview doesn't have a free quota tier. For more information on this error, head to: https://ai.google.dev/gemini-api/docs/rate-limits.",
94
+ status: 'RESOURCE_EXHAUSTED',
95
+ },
96
+ });
97
+
98
+ const errorMessage = JSON.stringify({
99
+ error: {
100
+ code: 429,
101
+ message: nestedErrorMessage,
102
+ status: 'Too Many Requests',
103
+ },
104
+ });
105
+
106
+ const result = parseAndFormatApiError(errorMessage, AuthType.USE_GEMINI);
107
+ expect(result).toContain('Gemini 2.5 Pro Preview');
108
+ expect(result).toContain(geminiMessage);
109
+ });
110
+
111
+ it('should format a StructuredError', () => {
112
+ const error: StructuredError = {
113
+ message: 'A structured error occurred',
114
+ status: 500,
115
+ };
116
+ const expected = '[API Error: A structured error occurred]';
117
+ expect(parseAndFormatApiError(error)).toBe(expected);
118
+ });
119
+
120
+ it('should format a 429 StructuredError with the vertex message', () => {
121
+ const error: StructuredError = {
122
+ message: 'Rate limit exceeded',
123
+ status: 429,
124
+ };
125
+ const result = parseAndFormatApiError(error, AuthType.USE_VERTEX_AI);
126
+ expect(result).toContain('[API Error: Rate limit exceeded]');
127
+ expect(result).toContain(vertexMessage);
128
+ });
129
+
130
+ it('should handle an unknown error type', () => {
131
+ const error = 12345;
132
+ const expected = '[API Error: An unknown error occurred.]';
133
+ expect(parseAndFormatApiError(error)).toBe(expected);
134
+ });
135
+
136
+ it('should format a 429 API error with Pro quota exceeded message for Google auth (Free tier)', () => {
137
+ const errorMessage =
138
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Quota exceeded for quota metric \'Gemini 2.5 Pro Requests\' and limit \'RequestsPerDay\' of service \'generativelanguage.googleapis.com\' for consumer \'project_number:123456789\'.","status":"RESOURCE_EXHAUSTED"}}';
139
+ const result = parseAndFormatApiError(
140
+ errorMessage,
141
+ AuthType.LOGIN_WITH_GOOGLE,
142
+ undefined,
143
+ 'gemini-2.5-pro',
144
+ DEFAULT_GEMINI_FLASH_MODEL,
145
+ );
146
+ expect(result).toContain(
147
+ "[API Error: Quota exceeded for quota metric 'Gemini 2.5 Pro Requests'",
148
+ );
149
+ expect(result).toContain(
150
+ 'You have reached your daily gemini-2.5-pro quota limit',
151
+ );
152
+ expect(result).toContain(
153
+ 'upgrade to a Gemini Code Assist Standard or Enterprise plan',
154
+ );
155
+ });
156
+
157
+ it('should format a regular 429 API error with standard message for Google auth', () => {
158
+ const errorMessage =
159
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Rate limit exceeded","status":"RESOURCE_EXHAUSTED"}}';
160
+ const result = parseAndFormatApiError(
161
+ errorMessage,
162
+ AuthType.LOGIN_WITH_GOOGLE,
163
+ undefined,
164
+ 'gemini-2.5-pro',
165
+ DEFAULT_GEMINI_FLASH_MODEL,
166
+ );
167
+ expect(result).toContain('[API Error: Rate limit exceeded');
168
+ expect(result).toContain(
169
+ 'Possible quota limitations in place or slow response times detected. Switching to the gemini-2.5-flash model',
170
+ );
171
+ expect(result).not.toContain(
172
+ 'You have reached your daily gemini-2.5-pro quota limit',
173
+ );
174
+ });
175
+
176
+ it('should format a 429 API error with generic quota exceeded message for Google auth', () => {
177
+ const errorMessage =
178
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Quota exceeded for quota metric \'GenerationRequests\' and limit \'RequestsPerDay\' of service \'generativelanguage.googleapis.com\' for consumer \'project_number:123456789\'.","status":"RESOURCE_EXHAUSTED"}}';
179
+ const result = parseAndFormatApiError(
180
+ errorMessage,
181
+ AuthType.LOGIN_WITH_GOOGLE,
182
+ undefined,
183
+ 'gemini-2.5-pro',
184
+ DEFAULT_GEMINI_FLASH_MODEL,
185
+ );
186
+ expect(result).toContain(
187
+ "[API Error: Quota exceeded for quota metric 'GenerationRequests'",
188
+ );
189
+ expect(result).toContain('You have reached your daily quota limit');
190
+ expect(result).not.toContain(
191
+ 'You have reached your daily Gemini 2.5 Pro quota limit',
192
+ );
193
+ });
194
+
195
+ it('should prioritize Pro quota message over generic quota message for Google auth', () => {
196
+ const errorMessage =
197
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Quota exceeded for quota metric \'Gemini 2.5 Pro Requests\' and limit \'RequestsPerDay\' of service \'generativelanguage.googleapis.com\' for consumer \'project_number:123456789\'.","status":"RESOURCE_EXHAUSTED"}}';
198
+ const result = parseAndFormatApiError(
199
+ errorMessage,
200
+ AuthType.LOGIN_WITH_GOOGLE,
201
+ undefined,
202
+ 'gemini-2.5-pro',
203
+ DEFAULT_GEMINI_FLASH_MODEL,
204
+ );
205
+ expect(result).toContain(
206
+ "[API Error: Quota exceeded for quota metric 'Gemini 2.5 Pro Requests'",
207
+ );
208
+ expect(result).toContain(
209
+ 'You have reached your daily gemini-2.5-pro quota limit',
210
+ );
211
+ expect(result).not.toContain('You have reached your daily quota limit');
212
+ });
213
+
214
+ it('should format a 429 API error with Pro quota exceeded message for Google auth (Standard tier)', () => {
215
+ const errorMessage =
216
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Quota exceeded for quota metric \'Gemini 2.5 Pro Requests\' and limit \'RequestsPerDay\' of service \'generativelanguage.googleapis.com\' for consumer \'project_number:123456789\'.","status":"RESOURCE_EXHAUSTED"}}';
217
+ const result = parseAndFormatApiError(
218
+ errorMessage,
219
+ AuthType.LOGIN_WITH_GOOGLE,
220
+ UserTierId.STANDARD,
221
+ 'gemini-2.5-pro',
222
+ DEFAULT_GEMINI_FLASH_MODEL,
223
+ );
224
+ expect(result).toContain(
225
+ "[API Error: Quota exceeded for quota metric 'Gemini 2.5 Pro Requests'",
226
+ );
227
+ expect(result).toContain(
228
+ 'You have reached your daily gemini-2.5-pro quota limit',
229
+ );
230
+ expect(result).toContain(
231
+ 'We appreciate you for choosing Gemini Code Assist and the Gemini CLI',
232
+ );
233
+ expect(result).not.toContain(
234
+ 'upgrade to a Gemini Code Assist Standard or Enterprise plan',
235
+ );
236
+ });
237
+
238
+ it('should format a 429 API error with Pro quota exceeded message for Google auth (Legacy tier)', () => {
239
+ const errorMessage =
240
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Quota exceeded for quota metric \'Gemini 2.5 Pro Requests\' and limit \'RequestsPerDay\' of service \'generativelanguage.googleapis.com\' for consumer \'project_number:123456789\'.","status":"RESOURCE_EXHAUSTED"}}';
241
+ const result = parseAndFormatApiError(
242
+ errorMessage,
243
+ AuthType.LOGIN_WITH_GOOGLE,
244
+ UserTierId.LEGACY,
245
+ 'gemini-2.5-pro',
246
+ DEFAULT_GEMINI_FLASH_MODEL,
247
+ );
248
+ expect(result).toContain(
249
+ "[API Error: Quota exceeded for quota metric 'Gemini 2.5 Pro Requests'",
250
+ );
251
+ expect(result).toContain(
252
+ 'You have reached your daily gemini-2.5-pro quota limit',
253
+ );
254
+ expect(result).toContain(
255
+ 'We appreciate you for choosing Gemini Code Assist and the Gemini CLI',
256
+ );
257
+ expect(result).not.toContain(
258
+ 'upgrade to a Gemini Code Assist Standard or Enterprise plan',
259
+ );
260
+ });
261
+
262
+ it('should handle different Gemini 2.5 version strings in Pro quota exceeded errors', () => {
263
+ const errorMessage25 =
264
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Quota exceeded for quota metric \'Gemini 2.5 Pro Requests\' and limit \'RequestsPerDay\' of service \'generativelanguage.googleapis.com\' for consumer \'project_number:123456789\'.","status":"RESOURCE_EXHAUSTED"}}';
265
+ const errorMessagePreview =
266
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Quota exceeded for quota metric \'Gemini 2.5-preview Pro Requests\' and limit \'RequestsPerDay\' of service \'generativelanguage.googleapis.com\' for consumer \'project_number:123456789\'.","status":"RESOURCE_EXHAUSTED"}}';
267
+
268
+ const result25 = parseAndFormatApiError(
269
+ errorMessage25,
270
+ AuthType.LOGIN_WITH_GOOGLE,
271
+ undefined,
272
+ 'gemini-2.5-pro',
273
+ DEFAULT_GEMINI_FLASH_MODEL,
274
+ );
275
+ const resultPreview = parseAndFormatApiError(
276
+ errorMessagePreview,
277
+ AuthType.LOGIN_WITH_GOOGLE,
278
+ undefined,
279
+ 'gemini-2.5-preview-pro',
280
+ DEFAULT_GEMINI_FLASH_MODEL,
281
+ );
282
+
283
+ expect(result25).toContain(
284
+ 'You have reached your daily gemini-2.5-pro quota limit',
285
+ );
286
+ expect(resultPreview).toContain(
287
+ 'You have reached your daily gemini-2.5-preview-pro quota limit',
288
+ );
289
+ expect(result25).toContain(
290
+ 'upgrade to a Gemini Code Assist Standard or Enterprise plan',
291
+ );
292
+ expect(resultPreview).toContain(
293
+ 'upgrade to a Gemini Code Assist Standard or Enterprise plan',
294
+ );
295
+ });
296
+
297
+ it('should not match non-Pro models with similar version strings', () => {
298
+ // Test that Flash models with similar version strings don't match
299
+ expect(
300
+ isProQuotaExceededError(
301
+ "Quota exceeded for quota metric 'Gemini 2.5 Flash Requests' and limit",
302
+ ),
303
+ ).toBe(false);
304
+ expect(
305
+ isProQuotaExceededError(
306
+ "Quota exceeded for quota metric 'Gemini 2.5-preview Flash Requests' and limit",
307
+ ),
308
+ ).toBe(false);
309
+
310
+ // Test other model types
311
+ expect(
312
+ isProQuotaExceededError(
313
+ "Quota exceeded for quota metric 'Gemini 2.5 Ultra Requests' and limit",
314
+ ),
315
+ ).toBe(false);
316
+ expect(
317
+ isProQuotaExceededError(
318
+ "Quota exceeded for quota metric 'Gemini 2.5 Standard Requests' and limit",
319
+ ),
320
+ ).toBe(false);
321
+
322
+ // Test generic quota messages
323
+ expect(
324
+ isProQuotaExceededError(
325
+ "Quota exceeded for quota metric 'GenerationRequests' and limit",
326
+ ),
327
+ ).toBe(false);
328
+ expect(
329
+ isProQuotaExceededError(
330
+ "Quota exceeded for quota metric 'EmbeddingRequests' and limit",
331
+ ),
332
+ ).toBe(false);
333
+ });
334
+
335
+ it('should format a generic quota exceeded message for Google auth (Standard tier)', () => {
336
+ const errorMessage =
337
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Quota exceeded for quota metric \'GenerationRequests\' and limit \'RequestsPerDay\' of service \'generativelanguage.googleapis.com\' for consumer \'project_number:123456789\'.","status":"RESOURCE_EXHAUSTED"}}';
338
+ const result = parseAndFormatApiError(
339
+ errorMessage,
340
+ AuthType.LOGIN_WITH_GOOGLE,
341
+ UserTierId.STANDARD,
342
+ 'gemini-2.5-pro',
343
+ DEFAULT_GEMINI_FLASH_MODEL,
344
+ );
345
+ expect(result).toContain(
346
+ "[API Error: Quota exceeded for quota metric 'GenerationRequests'",
347
+ );
348
+ expect(result).toContain('You have reached your daily quota limit');
349
+ expect(result).toContain(
350
+ 'We appreciate you for choosing Gemini Code Assist and the Gemini CLI',
351
+ );
352
+ expect(result).not.toContain(
353
+ 'upgrade to a Gemini Code Assist Standard or Enterprise plan',
354
+ );
355
+ });
356
+
357
+ it('should format a regular 429 API error with standard message for Google auth (Standard tier)', () => {
358
+ const errorMessage =
359
+ 'got status: 429 Too Many Requests. {"error":{"code":429,"message":"Rate limit exceeded","status":"RESOURCE_EXHAUSTED"}}';
360
+ const result = parseAndFormatApiError(
361
+ errorMessage,
362
+ AuthType.LOGIN_WITH_GOOGLE,
363
+ UserTierId.STANDARD,
364
+ 'gemini-2.5-pro',
365
+ DEFAULT_GEMINI_FLASH_MODEL,
366
+ );
367
+ expect(result).toContain('[API Error: Rate limit exceeded');
368
+ expect(result).toContain(
369
+ 'We appreciate you for choosing Gemini Code Assist and the Gemini CLI',
370
+ );
371
+ expect(result).not.toContain(
372
+ 'upgrade to a Gemini Code Assist Standard or Enterprise plan',
373
+ );
374
+ });
375
+ });
projects/ui/qwen-code/packages/core/src/utils/errorParsing.ts ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ isProQuotaExceededError,
9
+ isGenericQuotaExceededError,
10
+ isApiError,
11
+ isStructuredError,
12
+ } from './quotaErrorDetection.js';
13
+ import {
14
+ DEFAULT_GEMINI_MODEL,
15
+ DEFAULT_GEMINI_FLASH_MODEL,
16
+ } from '../config/models.js';
17
+ import { UserTierId } from '../code_assist/types.js';
18
+ import { AuthType } from '../core/contentGenerator.js';
19
+
20
+ // Free Tier message functions
21
+ const getRateLimitErrorMessageGoogleFree = (
22
+ fallbackModel: string = DEFAULT_GEMINI_FLASH_MODEL,
23
+ ) =>
24
+ `\nPossible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session.`;
25
+
26
+ const getRateLimitErrorMessageGoogleProQuotaFree = (
27
+ currentModel: string = DEFAULT_GEMINI_MODEL,
28
+ fallbackModel: string = DEFAULT_GEMINI_FLASH_MODEL,
29
+ ) =>
30
+ `\nYou have reached your daily ${currentModel} quota limit. You will be switched to the ${fallbackModel} model for the rest of this session. To increase your limits, upgrade to a Gemini Code Assist Standard or Enterprise plan with higher limits at https://goo.gle/set-up-gemini-code-assist, or use /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
31
+
32
+ const getRateLimitErrorMessageGoogleGenericQuotaFree = () =>
33
+ `\nYou have reached your daily quota limit. To increase your limits, upgrade to a Gemini Code Assist Standard or Enterprise plan with higher limits at https://goo.gle/set-up-gemini-code-assist, or use /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
34
+
35
+ // Legacy/Standard Tier message functions
36
+ const getRateLimitErrorMessageGooglePaid = (
37
+ fallbackModel: string = DEFAULT_GEMINI_FLASH_MODEL,
38
+ ) =>
39
+ `\nPossible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session. We appreciate you for choosing Gemini Code Assist and the Gemini CLI.`;
40
+
41
+ const getRateLimitErrorMessageGoogleProQuotaPaid = (
42
+ currentModel: string = DEFAULT_GEMINI_MODEL,
43
+ fallbackModel: string = DEFAULT_GEMINI_FLASH_MODEL,
44
+ ) =>
45
+ `\nYou have reached your daily ${currentModel} quota limit. You will be switched to the ${fallbackModel} model for the rest of this session. We appreciate you for choosing Gemini Code Assist and the Gemini CLI. To continue accessing the ${currentModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
46
+
47
+ const getRateLimitErrorMessageGoogleGenericQuotaPaid = (
48
+ currentModel: string = DEFAULT_GEMINI_MODEL,
49
+ ) =>
50
+ `\nYou have reached your daily quota limit. We appreciate you for choosing Gemini Code Assist and the Gemini CLI. To continue accessing the ${currentModel} model today, consider using /auth to switch to using a paid API key from AI Studio at https://aistudio.google.com/apikey`;
51
+ const RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI =
52
+ '\nPlease wait and try again later. To increase your limits, request a quota increase through AI Studio, or switch to another /auth method';
53
+ const RATE_LIMIT_ERROR_MESSAGE_VERTEX =
54
+ '\nPlease wait and try again later. To increase your limits, request a quota increase through Vertex, or switch to another /auth method';
55
+ const getRateLimitErrorMessageDefault = (
56
+ fallbackModel: string = DEFAULT_GEMINI_FLASH_MODEL,
57
+ ) =>
58
+ `\nPossible quota limitations in place or slow response times detected. Switching to the ${fallbackModel} model for the rest of this session.`;
59
+
60
+ function getRateLimitMessage(
61
+ authType?: AuthType,
62
+ error?: unknown,
63
+ userTier?: UserTierId,
64
+ currentModel?: string,
65
+ fallbackModel?: string,
66
+ ): string {
67
+ switch (authType) {
68
+ case AuthType.LOGIN_WITH_GOOGLE: {
69
+ // Determine if user is on a paid tier (Legacy or Standard) - default to FREE if not specified
70
+ const isPaidTier =
71
+ userTier === UserTierId.LEGACY || userTier === UserTierId.STANDARD;
72
+
73
+ if (isProQuotaExceededError(error)) {
74
+ return isPaidTier
75
+ ? getRateLimitErrorMessageGoogleProQuotaPaid(
76
+ currentModel || DEFAULT_GEMINI_MODEL,
77
+ fallbackModel,
78
+ )
79
+ : getRateLimitErrorMessageGoogleProQuotaFree(
80
+ currentModel || DEFAULT_GEMINI_MODEL,
81
+ fallbackModel,
82
+ );
83
+ } else if (isGenericQuotaExceededError(error)) {
84
+ return isPaidTier
85
+ ? getRateLimitErrorMessageGoogleGenericQuotaPaid(
86
+ currentModel || DEFAULT_GEMINI_MODEL,
87
+ )
88
+ : getRateLimitErrorMessageGoogleGenericQuotaFree();
89
+ } else {
90
+ return isPaidTier
91
+ ? getRateLimitErrorMessageGooglePaid(fallbackModel)
92
+ : getRateLimitErrorMessageGoogleFree(fallbackModel);
93
+ }
94
+ }
95
+ case AuthType.USE_GEMINI:
96
+ return RATE_LIMIT_ERROR_MESSAGE_USE_GEMINI;
97
+ case AuthType.USE_VERTEX_AI:
98
+ return RATE_LIMIT_ERROR_MESSAGE_VERTEX;
99
+ default:
100
+ return getRateLimitErrorMessageDefault(fallbackModel);
101
+ }
102
+ }
103
+
104
+ export function parseAndFormatApiError(
105
+ error: unknown,
106
+ authType?: AuthType,
107
+ userTier?: UserTierId,
108
+ currentModel?: string,
109
+ fallbackModel?: string,
110
+ ): string {
111
+ if (isStructuredError(error)) {
112
+ let text = `[API Error: ${error.message}]`;
113
+ if (error.status === 429) {
114
+ text += getRateLimitMessage(
115
+ authType,
116
+ error,
117
+ userTier,
118
+ currentModel,
119
+ fallbackModel,
120
+ );
121
+ }
122
+ return text;
123
+ }
124
+
125
+ // The error message might be a string containing a JSON object.
126
+ if (typeof error === 'string') {
127
+ const jsonStart = error.indexOf('{');
128
+ if (jsonStart === -1) {
129
+ return `[API Error: ${error}]`; // Not a JSON error, return as is.
130
+ }
131
+
132
+ const jsonString = error.substring(jsonStart);
133
+
134
+ try {
135
+ const parsedError = JSON.parse(jsonString) as unknown;
136
+ if (isApiError(parsedError)) {
137
+ let finalMessage = parsedError.error.message;
138
+ try {
139
+ // See if the message is a stringified JSON with another error
140
+ const nestedError = JSON.parse(finalMessage) as unknown;
141
+ if (isApiError(nestedError)) {
142
+ finalMessage = nestedError.error.message;
143
+ }
144
+ } catch (_e) {
145
+ // It's not a nested JSON error, so we just use the message as is.
146
+ }
147
+ let text = `[API Error: ${finalMessage} (Status: ${parsedError.error.status})]`;
148
+ if (parsedError.error.code === 429) {
149
+ text += getRateLimitMessage(
150
+ authType,
151
+ parsedError,
152
+ userTier,
153
+ currentModel,
154
+ fallbackModel,
155
+ );
156
+ }
157
+ return text;
158
+ }
159
+ } catch (_e) {
160
+ // Not a valid JSON, fall through and return the original message.
161
+ }
162
+ return `[API Error: ${error}]`;
163
+ }
164
+
165
+ return '[API Error: An unknown error occurred.]';
166
+ }
projects/ui/qwen-code/packages/core/src/utils/errorReporting.test.ts ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fs from 'node:fs/promises';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { reportError } from './errorReporting.js';
12
+
13
+ // Use a type alias for SpyInstance as it's not directly exported
14
+ type SpyInstance = ReturnType<typeof vi.spyOn>;
15
+
16
+ describe('reportError', () => {
17
+ let consoleErrorSpy: SpyInstance;
18
+ let testDir: string;
19
+ const MOCK_TIMESTAMP = '2025-01-01T00-00-00-000Z';
20
+
21
+ beforeEach(async () => {
22
+ // Create a temporary directory for logs
23
+ testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'gemini-report-test-'));
24
+ vi.resetAllMocks();
25
+ consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
26
+ vi.spyOn(Date.prototype, 'toISOString').mockReturnValue(MOCK_TIMESTAMP);
27
+ });
28
+
29
+ afterEach(async () => {
30
+ vi.restoreAllMocks();
31
+ // Clean up the temporary directory
32
+ await fs.rm(testDir, { recursive: true, force: true });
33
+ });
34
+
35
+ const getExpectedReportPath = (type: string) =>
36
+ path.join(testDir, `gemini-client-error-${type}-${MOCK_TIMESTAMP}.json`);
37
+
38
+ it('should generate a report and log the path', async () => {
39
+ const error = new Error('Test error');
40
+ error.stack = 'Test stack';
41
+ const baseMessage = 'An error occurred.';
42
+ const context = { data: 'test context' };
43
+ const type = 'test-type';
44
+ const expectedReportPath = getExpectedReportPath(type);
45
+
46
+ await reportError(error, baseMessage, context, type, testDir);
47
+
48
+ // Verify the file was written
49
+ const reportContent = await fs.readFile(expectedReportPath, 'utf-8');
50
+ const parsedReport = JSON.parse(reportContent);
51
+
52
+ expect(parsedReport).toEqual({
53
+ error: { message: 'Test error', stack: 'Test stack' },
54
+ context,
55
+ });
56
+
57
+ // Verify the console log
58
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
59
+ `${baseMessage} Full report available at: ${expectedReportPath}`,
60
+ );
61
+ });
62
+
63
+ it('should handle errors that are plain objects with a message property', async () => {
64
+ const error = { message: 'Test plain object error' };
65
+ const baseMessage = 'Another error.';
66
+ const type = 'general';
67
+ const expectedReportPath = getExpectedReportPath(type);
68
+
69
+ await reportError(error, baseMessage, undefined, type, testDir);
70
+
71
+ const reportContent = await fs.readFile(expectedReportPath, 'utf-8');
72
+ const parsedReport = JSON.parse(reportContent);
73
+
74
+ expect(parsedReport).toEqual({
75
+ error: { message: 'Test plain object error' },
76
+ });
77
+
78
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
79
+ `${baseMessage} Full report available at: ${expectedReportPath}`,
80
+ );
81
+ });
82
+
83
+ it('should handle string errors', async () => {
84
+ const error = 'Just a string error';
85
+ const baseMessage = 'String error occurred.';
86
+ const type = 'general';
87
+ const expectedReportPath = getExpectedReportPath(type);
88
+
89
+ await reportError(error, baseMessage, undefined, type, testDir);
90
+
91
+ const reportContent = await fs.readFile(expectedReportPath, 'utf-8');
92
+ const parsedReport = JSON.parse(reportContent);
93
+
94
+ expect(parsedReport).toEqual({
95
+ error: { message: 'Just a string error' },
96
+ });
97
+
98
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
99
+ `${baseMessage} Full report available at: ${expectedReportPath}`,
100
+ );
101
+ });
102
+
103
+ it('should log fallback message if writing report fails', async () => {
104
+ const error = new Error('Main error');
105
+ const baseMessage = 'Failed operation.';
106
+ const context = ['some context'];
107
+ const type = 'general';
108
+ const nonExistentDir = path.join(testDir, 'non-existent-dir');
109
+
110
+ await reportError(error, baseMessage, context, type, nonExistentDir);
111
+
112
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
113
+ `${baseMessage} Additionally, failed to write detailed error report:`,
114
+ expect.any(Error), // The actual write error
115
+ );
116
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
117
+ 'Original error that triggered report generation:',
118
+ error,
119
+ );
120
+ expect(consoleErrorSpy).toHaveBeenCalledWith('Original context:', context);
121
+ });
122
+
123
+ it('should handle stringification failure of report content (e.g. BigInt in context)', async () => {
124
+ const error = new Error('Main error');
125
+ error.stack = 'Main stack';
126
+ const baseMessage = 'Failed operation with BigInt.';
127
+ const context = { a: BigInt(1) }; // BigInt cannot be stringified by JSON.stringify
128
+ const type = 'bigint-fail';
129
+ const stringifyError = new TypeError(
130
+ 'Do not know how to serialize a BigInt',
131
+ );
132
+ const expectedMinimalReportPath = getExpectedReportPath(type);
133
+
134
+ // Simulate JSON.stringify throwing an error for the full report
135
+ const originalJsonStringify = JSON.stringify;
136
+ let callCount = 0;
137
+ vi.spyOn(JSON, 'stringify').mockImplementation((value, replacer, space) => {
138
+ callCount++;
139
+ if (callCount === 1) {
140
+ // First call is for the full report content
141
+ throw stringifyError;
142
+ }
143
+ // Subsequent calls (for minimal report) should succeed
144
+ return originalJsonStringify(value, replacer, space);
145
+ });
146
+
147
+ await reportError(error, baseMessage, context, type, testDir);
148
+
149
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
150
+ `${baseMessage} Could not stringify report content (likely due to context):`,
151
+ stringifyError,
152
+ );
153
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
154
+ 'Original error that triggered report generation:',
155
+ error,
156
+ );
157
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
158
+ 'Original context could not be stringified or included in report.',
159
+ );
160
+
161
+ // Check that it writes a minimal report
162
+ const reportContent = await fs.readFile(expectedMinimalReportPath, 'utf-8');
163
+ const parsedReport = JSON.parse(reportContent);
164
+ expect(parsedReport).toEqual({
165
+ error: { message: error.message, stack: error.stack },
166
+ });
167
+
168
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
169
+ `${baseMessage} Partial report (excluding context) available at: ${expectedMinimalReportPath}`,
170
+ );
171
+ });
172
+
173
+ it('should generate a report without context if context is not provided', async () => {
174
+ const error = new Error('Error without context');
175
+ error.stack = 'No context stack';
176
+ const baseMessage = 'Simple error.';
177
+ const type = 'general';
178
+ const expectedReportPath = getExpectedReportPath(type);
179
+
180
+ await reportError(error, baseMessage, undefined, type, testDir);
181
+
182
+ const reportContent = await fs.readFile(expectedReportPath, 'utf-8');
183
+ const parsedReport = JSON.parse(reportContent);
184
+
185
+ expect(parsedReport).toEqual({
186
+ error: { message: 'Error without context', stack: 'No context stack' },
187
+ });
188
+
189
+ expect(consoleErrorSpy).toHaveBeenCalledWith(
190
+ `${baseMessage} Full report available at: ${expectedReportPath}`,
191
+ );
192
+ });
193
+ });
projects/ui/qwen-code/packages/core/src/utils/errorReporting.ts ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import fs from 'node:fs/promises';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { Content } from '@google/genai';
11
+
12
+ interface ErrorReportData {
13
+ error: { message: string; stack?: string } | { message: string };
14
+ context?: unknown;
15
+ additionalInfo?: Record<string, unknown>;
16
+ }
17
+
18
+ /**
19
+ * Generates an error report, writes it to a temporary file, and logs information to console.error.
20
+ * @param error The error object.
21
+ * @param context The relevant context (e.g., chat history, request contents).
22
+ * @param type A string to identify the type of error (e.g., 'startChat', 'generateJson-api').
23
+ * @param baseMessage The initial message to log to console.error before the report path.
24
+ */
25
+ export async function reportError(
26
+ error: Error | unknown,
27
+ baseMessage: string,
28
+ context?: Content[] | Record<string, unknown> | unknown[],
29
+ type = 'general',
30
+ reportingDir = os.tmpdir(), // for testing
31
+ ): Promise<void> {
32
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
33
+ const reportFileName = `gemini-client-error-${type}-${timestamp}.json`;
34
+ const reportPath = path.join(reportingDir, reportFileName);
35
+
36
+ let errorToReport: { message: string; stack?: string };
37
+ if (error instanceof Error) {
38
+ errorToReport = { message: error.message, stack: error.stack };
39
+ } else if (
40
+ typeof error === 'object' &&
41
+ error !== null &&
42
+ 'message' in error
43
+ ) {
44
+ errorToReport = {
45
+ message: String((error as { message: unknown }).message),
46
+ };
47
+ } else {
48
+ errorToReport = { message: String(error) };
49
+ }
50
+
51
+ const reportContent: ErrorReportData = { error: errorToReport };
52
+
53
+ if (context) {
54
+ reportContent.context = context;
55
+ }
56
+
57
+ let stringifiedReportContent: string;
58
+ try {
59
+ stringifiedReportContent = JSON.stringify(reportContent, null, 2);
60
+ } catch (stringifyError) {
61
+ // This can happen if context contains something like BigInt
62
+ console.error(
63
+ `${baseMessage} Could not stringify report content (likely due to context):`,
64
+ stringifyError,
65
+ );
66
+ console.error('Original error that triggered report generation:', error);
67
+ if (context) {
68
+ console.error(
69
+ 'Original context could not be stringified or included in report.',
70
+ );
71
+ }
72
+ // Fallback: try to report only the error if context was the issue
73
+ try {
74
+ const minimalReportContent = { error: errorToReport };
75
+ stringifiedReportContent = JSON.stringify(minimalReportContent, null, 2);
76
+ // Still try to write the minimal report
77
+ await fs.writeFile(reportPath, stringifiedReportContent);
78
+ console.error(
79
+ `${baseMessage} Partial report (excluding context) available at: ${reportPath}`,
80
+ );
81
+ } catch (minimalWriteError) {
82
+ console.error(
83
+ `${baseMessage} Failed to write even a minimal error report:`,
84
+ minimalWriteError,
85
+ );
86
+ }
87
+ return;
88
+ }
89
+
90
+ try {
91
+ await fs.writeFile(reportPath, stringifiedReportContent);
92
+ console.error(`${baseMessage} Full report available at: ${reportPath}`);
93
+ } catch (writeError) {
94
+ console.error(
95
+ `${baseMessage} Additionally, failed to write detailed error report:`,
96
+ writeError,
97
+ );
98
+ // Log the original error as a fallback if report writing fails
99
+ console.error('Original error that triggered report generation:', error);
100
+ if (context) {
101
+ // Context was stringifiable, but writing the file failed.
102
+ // We already have stringifiedReportContent, but it might be too large for console.
103
+ // So, we try to log the original context object, and if that fails, its stringified version (truncated).
104
+ try {
105
+ console.error('Original context:', context);
106
+ } catch {
107
+ try {
108
+ console.error(
109
+ 'Original context (stringified, truncated):',
110
+ JSON.stringify(context).substring(0, 1000),
111
+ );
112
+ } catch {
113
+ console.error('Original context could not be logged or stringified.');
114
+ }
115
+ }
116
+ }
117
+ }
118
+ }
projects/ui/qwen-code/packages/core/src/utils/errors.ts ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ interface GaxiosError {
8
+ response?: {
9
+ data?: unknown;
10
+ };
11
+ }
12
+
13
+ export function isNodeError(error: unknown): error is NodeJS.ErrnoException {
14
+ return error instanceof Error && 'code' in error;
15
+ }
16
+
17
+ export function getErrorMessage(error: unknown): string {
18
+ if (error instanceof Error) {
19
+ return error.message;
20
+ }
21
+ try {
22
+ return String(error);
23
+ } catch {
24
+ return 'Failed to get error details';
25
+ }
26
+ }
27
+
28
+ export class ForbiddenError extends Error {}
29
+ export class UnauthorizedError extends Error {}
30
+ export class BadRequestError extends Error {}
31
+
32
+ interface ResponseData {
33
+ error?: {
34
+ code?: number;
35
+ message?: string;
36
+ };
37
+ }
38
+
39
+ export function toFriendlyError(error: unknown): unknown {
40
+ if (error && typeof error === 'object' && 'response' in error) {
41
+ const gaxiosError = error as GaxiosError;
42
+ const data = parseResponseData(gaxiosError);
43
+ if (data.error && data.error.message && data.error.code) {
44
+ switch (data.error.code) {
45
+ case 400:
46
+ return new BadRequestError(data.error.message);
47
+ case 401:
48
+ return new UnauthorizedError(data.error.message);
49
+ case 403:
50
+ // It's import to pass the message here since it might
51
+ // explain the cause like "the cloud project you're
52
+ // using doesn't have code assist enabled".
53
+ return new ForbiddenError(data.error.message);
54
+ default:
55
+ }
56
+ }
57
+ }
58
+ return error;
59
+ }
60
+
61
+ function parseResponseData(error: GaxiosError): ResponseData {
62
+ // Inexplicably, Gaxios sometimes doesn't JSONify the response data.
63
+ if (typeof error.response?.data === 'string') {
64
+ return JSON.parse(error.response?.data) as ResponseData;
65
+ }
66
+ return error.response?.data as ResponseData;
67
+ }
projects/ui/qwen-code/packages/core/src/utils/fetch.ts ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { getErrorMessage, isNodeError } from './errors.js';
8
+ import { URL } from 'url';
9
+
10
+ const PRIVATE_IP_RANGES = [
11
+ /^10\./,
12
+ /^127\./,
13
+ /^172\.(1[6-9]|2[0-9]|3[0-1])\./,
14
+ /^192\.168\./,
15
+ /^::1$/,
16
+ /^fc00:/,
17
+ /^fe80:/,
18
+ ];
19
+
20
+ export class FetchError extends Error {
21
+ constructor(
22
+ message: string,
23
+ public code?: string,
24
+ ) {
25
+ super(message);
26
+ this.name = 'FetchError';
27
+ }
28
+ }
29
+
30
+ export function isPrivateIp(url: string): boolean {
31
+ try {
32
+ const hostname = new URL(url).hostname;
33
+ return PRIVATE_IP_RANGES.some((range) => range.test(hostname));
34
+ } catch (_e) {
35
+ return false;
36
+ }
37
+ }
38
+
39
+ export async function fetchWithTimeout(
40
+ url: string,
41
+ timeout: number,
42
+ ): Promise<Response> {
43
+ const controller = new AbortController();
44
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
45
+
46
+ try {
47
+ const response = await fetch(url, { signal: controller.signal });
48
+ return response;
49
+ } catch (error) {
50
+ if (isNodeError(error) && error.code === 'ABORT_ERR') {
51
+ throw new FetchError(`Request timed out after ${timeout}ms`, 'ETIMEDOUT');
52
+ }
53
+ throw new FetchError(getErrorMessage(error));
54
+ } finally {
55
+ clearTimeout(timeoutId);
56
+ }
57
+ }
projects/ui/qwen-code/packages/core/src/utils/fileUtils.test.ts ADDED
@@ -0,0 +1,591 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ describe,
9
+ it,
10
+ expect,
11
+ vi,
12
+ beforeEach,
13
+ afterEach,
14
+ type Mock,
15
+ } from 'vitest';
16
+
17
+ import * as actualNodeFs from 'node:fs'; // For setup/teardown
18
+ import fsPromises from 'node:fs/promises';
19
+ import path from 'node:path';
20
+ import os from 'node:os';
21
+ import mime from 'mime-types';
22
+
23
+ import {
24
+ isWithinRoot,
25
+ isBinaryFile,
26
+ detectFileType,
27
+ processSingleFileContent,
28
+ } from './fileUtils.js';
29
+ import { StandardFileSystemService } from '../services/fileSystemService.js';
30
+
31
+ vi.mock('mime-types', () => ({
32
+ default: { lookup: vi.fn() },
33
+ lookup: vi.fn(),
34
+ }));
35
+
36
+ const mockMimeLookup = mime.lookup as Mock;
37
+
38
+ describe('fileUtils', () => {
39
+ let tempRootDir: string;
40
+ const originalProcessCwd = process.cwd;
41
+
42
+ let testTextFilePath: string;
43
+ let testImageFilePath: string;
44
+ let testPdfFilePath: string;
45
+ let testBinaryFilePath: string;
46
+ let nonexistentFilePath: string;
47
+ let directoryPath: string;
48
+
49
+ beforeEach(() => {
50
+ vi.resetAllMocks(); // Reset all mocks, including mime.lookup
51
+
52
+ tempRootDir = actualNodeFs.mkdtempSync(
53
+ path.join(os.tmpdir(), 'fileUtils-test-'),
54
+ );
55
+ process.cwd = vi.fn(() => tempRootDir); // Mock cwd if necessary for relative path logic within tests
56
+
57
+ testTextFilePath = path.join(tempRootDir, 'test.txt');
58
+ testImageFilePath = path.join(tempRootDir, 'image.png');
59
+ testPdfFilePath = path.join(tempRootDir, 'document.pdf');
60
+ testBinaryFilePath = path.join(tempRootDir, 'app.exe');
61
+ nonexistentFilePath = path.join(tempRootDir, 'nonexistent.txt');
62
+ directoryPath = path.join(tempRootDir, 'subdir');
63
+
64
+ actualNodeFs.mkdirSync(directoryPath, { recursive: true }); // Ensure subdir exists
65
+ });
66
+
67
+ afterEach(() => {
68
+ if (actualNodeFs.existsSync(tempRootDir)) {
69
+ actualNodeFs.rmSync(tempRootDir, { recursive: true, force: true });
70
+ }
71
+ process.cwd = originalProcessCwd;
72
+ vi.restoreAllMocks(); // Restore any spies
73
+ });
74
+
75
+ describe('isWithinRoot', () => {
76
+ const root = path.resolve('/project/root');
77
+
78
+ it('should return true for paths directly within the root', () => {
79
+ expect(isWithinRoot(path.join(root, 'file.txt'), root)).toBe(true);
80
+ expect(isWithinRoot(path.join(root, 'subdir', 'file.txt'), root)).toBe(
81
+ true,
82
+ );
83
+ });
84
+
85
+ it('should return true for the root path itself', () => {
86
+ expect(isWithinRoot(root, root)).toBe(true);
87
+ });
88
+
89
+ it('should return false for paths outside the root', () => {
90
+ expect(
91
+ isWithinRoot(path.resolve('/project/other', 'file.txt'), root),
92
+ ).toBe(false);
93
+ expect(isWithinRoot(path.resolve('/unrelated', 'file.txt'), root)).toBe(
94
+ false,
95
+ );
96
+ });
97
+
98
+ it('should return false for paths that only partially match the root prefix', () => {
99
+ expect(
100
+ isWithinRoot(
101
+ path.resolve('/project/root-but-actually-different'),
102
+ root,
103
+ ),
104
+ ).toBe(false);
105
+ });
106
+
107
+ it('should handle paths with trailing slashes correctly', () => {
108
+ expect(isWithinRoot(path.join(root, 'file.txt') + path.sep, root)).toBe(
109
+ true,
110
+ );
111
+ expect(isWithinRoot(root + path.sep, root)).toBe(true);
112
+ });
113
+
114
+ it('should handle different path separators (POSIX vs Windows)', () => {
115
+ const posixRoot = '/project/root';
116
+ const posixPathInside = '/project/root/file.txt';
117
+ const posixPathOutside = '/project/other/file.txt';
118
+ expect(isWithinRoot(posixPathInside, posixRoot)).toBe(true);
119
+ expect(isWithinRoot(posixPathOutside, posixRoot)).toBe(false);
120
+ });
121
+
122
+ it('should return false for a root path that is a sub-path of the path to check', () => {
123
+ const pathToCheck = path.resolve('/project/root/sub');
124
+ const rootSub = path.resolve('/project/root');
125
+ expect(isWithinRoot(pathToCheck, rootSub)).toBe(true);
126
+
127
+ const pathToCheckSuper = path.resolve('/project/root');
128
+ const rootSuper = path.resolve('/project/root/sub');
129
+ expect(isWithinRoot(pathToCheckSuper, rootSuper)).toBe(false);
130
+ });
131
+ });
132
+
133
+ describe('isBinaryFile', () => {
134
+ let filePathForBinaryTest: string;
135
+
136
+ beforeEach(() => {
137
+ filePathForBinaryTest = path.join(tempRootDir, 'binaryCheck.tmp');
138
+ });
139
+
140
+ afterEach(() => {
141
+ if (actualNodeFs.existsSync(filePathForBinaryTest)) {
142
+ actualNodeFs.unlinkSync(filePathForBinaryTest);
143
+ }
144
+ });
145
+
146
+ it('should return false for an empty file', async () => {
147
+ actualNodeFs.writeFileSync(filePathForBinaryTest, '');
148
+ expect(await isBinaryFile(filePathForBinaryTest)).toBe(false);
149
+ });
150
+
151
+ it('should return false for a typical text file', async () => {
152
+ actualNodeFs.writeFileSync(
153
+ filePathForBinaryTest,
154
+ 'Hello, world!\nThis is a test file with normal text content.',
155
+ );
156
+ expect(await isBinaryFile(filePathForBinaryTest)).toBe(false);
157
+ });
158
+
159
+ it('should return true for a file with many null bytes', async () => {
160
+ const binaryContent = Buffer.from([
161
+ 0x48, 0x65, 0x00, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00,
162
+ ]); // "He\0llo\0\0\0\0\0"
163
+ actualNodeFs.writeFileSync(filePathForBinaryTest, binaryContent);
164
+ expect(await isBinaryFile(filePathForBinaryTest)).toBe(true);
165
+ });
166
+
167
+ it('should return true for a file with high percentage of non-printable ASCII', async () => {
168
+ const binaryContent = Buffer.from([
169
+ 0x41, 0x42, 0x01, 0x02, 0x03, 0x04, 0x05, 0x43, 0x44, 0x06,
170
+ ]); // AB\x01\x02\x03\x04\x05CD\x06
171
+ actualNodeFs.writeFileSync(filePathForBinaryTest, binaryContent);
172
+ expect(await isBinaryFile(filePathForBinaryTest)).toBe(true);
173
+ });
174
+
175
+ it('should return false if file access fails (e.g., ENOENT)', async () => {
176
+ // Ensure the file does not exist
177
+ if (actualNodeFs.existsSync(filePathForBinaryTest)) {
178
+ actualNodeFs.unlinkSync(filePathForBinaryTest);
179
+ }
180
+ expect(await isBinaryFile(filePathForBinaryTest)).toBe(false);
181
+ });
182
+ });
183
+
184
+ describe('detectFileType', () => {
185
+ let filePathForDetectTest: string;
186
+
187
+ beforeEach(() => {
188
+ filePathForDetectTest = path.join(tempRootDir, 'detectType.tmp');
189
+ // Default: create as a text file for isBinaryFile fallback
190
+ actualNodeFs.writeFileSync(filePathForDetectTest, 'Plain text content');
191
+ });
192
+
193
+ afterEach(() => {
194
+ if (actualNodeFs.existsSync(filePathForDetectTest)) {
195
+ actualNodeFs.unlinkSync(filePathForDetectTest);
196
+ }
197
+ vi.restoreAllMocks(); // Restore spies on actualNodeFs
198
+ });
199
+
200
+ it('should detect typescript type by extension (ts, mts, cts, tsx)', async () => {
201
+ expect(await detectFileType('file.ts')).toBe('text');
202
+ expect(await detectFileType('file.test.ts')).toBe('text');
203
+ expect(await detectFileType('file.mts')).toBe('text');
204
+ expect(await detectFileType('vite.config.mts')).toBe('text');
205
+ expect(await detectFileType('file.cts')).toBe('text');
206
+ expect(await detectFileType('component.tsx')).toBe('text');
207
+ });
208
+
209
+ it('should detect image type by extension (png)', async () => {
210
+ mockMimeLookup.mockReturnValueOnce('image/png');
211
+ expect(await detectFileType('file.png')).toBe('image');
212
+ });
213
+
214
+ it('should detect image type by extension (jpeg)', async () => {
215
+ mockMimeLookup.mockReturnValueOnce('image/jpeg');
216
+ expect(await detectFileType('file.jpg')).toBe('image');
217
+ });
218
+
219
+ it('should detect svg type by extension', async () => {
220
+ expect(await detectFileType('image.svg')).toBe('svg');
221
+ expect(await detectFileType('image.icon.svg')).toBe('svg');
222
+ });
223
+
224
+ it('should detect pdf type by extension', async () => {
225
+ mockMimeLookup.mockReturnValueOnce('application/pdf');
226
+ expect(await detectFileType('file.pdf')).toBe('pdf');
227
+ });
228
+
229
+ it('should detect audio type by extension', async () => {
230
+ mockMimeLookup.mockReturnValueOnce('audio/mpeg');
231
+ expect(await detectFileType('song.mp3')).toBe('audio');
232
+ });
233
+
234
+ it('should detect video type by extension', async () => {
235
+ mockMimeLookup.mockReturnValueOnce('video/mp4');
236
+ expect(await detectFileType('movie.mp4')).toBe('video');
237
+ });
238
+
239
+ it('should detect known binary extensions as binary (e.g. .zip)', async () => {
240
+ mockMimeLookup.mockReturnValueOnce('application/zip');
241
+ expect(await detectFileType('archive.zip')).toBe('binary');
242
+ });
243
+ it('should detect known binary extensions as binary (e.g. .exe)', async () => {
244
+ mockMimeLookup.mockReturnValueOnce('application/octet-stream'); // Common for .exe
245
+ expect(await detectFileType('app.exe')).toBe('binary');
246
+ });
247
+
248
+ it('should use isBinaryFile for unknown extensions and detect as binary', async () => {
249
+ mockMimeLookup.mockReturnValueOnce(false); // Unknown mime type
250
+ // Create a file that isBinaryFile will identify as binary
251
+ const binaryContent = Buffer.from([
252
+ 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a,
253
+ ]);
254
+ actualNodeFs.writeFileSync(filePathForDetectTest, binaryContent);
255
+ expect(await detectFileType(filePathForDetectTest)).toBe('binary');
256
+ });
257
+
258
+ it('should default to text if mime type is unknown and content is not binary', async () => {
259
+ mockMimeLookup.mockReturnValueOnce(false); // Unknown mime type
260
+ // filePathForDetectTest is already a text file by default from beforeEach
261
+ expect(await detectFileType(filePathForDetectTest)).toBe('text');
262
+ });
263
+ });
264
+
265
+ describe('processSingleFileContent', () => {
266
+ beforeEach(() => {
267
+ // Ensure files exist for statSync checks before readFile might be mocked
268
+ if (actualNodeFs.existsSync(testTextFilePath))
269
+ actualNodeFs.unlinkSync(testTextFilePath);
270
+ if (actualNodeFs.existsSync(testImageFilePath))
271
+ actualNodeFs.unlinkSync(testImageFilePath);
272
+ if (actualNodeFs.existsSync(testPdfFilePath))
273
+ actualNodeFs.unlinkSync(testPdfFilePath);
274
+ if (actualNodeFs.existsSync(testBinaryFilePath))
275
+ actualNodeFs.unlinkSync(testBinaryFilePath);
276
+ });
277
+
278
+ it('should read a text file successfully', async () => {
279
+ const content = 'Line 1\\nLine 2\\nLine 3';
280
+ actualNodeFs.writeFileSync(testTextFilePath, content);
281
+ const result = await processSingleFileContent(
282
+ testTextFilePath,
283
+ tempRootDir,
284
+ new StandardFileSystemService(),
285
+ );
286
+ expect(result.llmContent).toBe(content);
287
+ expect(result.returnDisplay).toBe('');
288
+ expect(result.error).toBeUndefined();
289
+ });
290
+
291
+ it('should handle file not found', async () => {
292
+ const result = await processSingleFileContent(
293
+ nonexistentFilePath,
294
+ tempRootDir,
295
+ new StandardFileSystemService(),
296
+ );
297
+ expect(result.error).toContain('File not found');
298
+ expect(result.returnDisplay).toContain('File not found');
299
+ });
300
+
301
+ it('should handle read errors for text files', async () => {
302
+ actualNodeFs.writeFileSync(testTextFilePath, 'content'); // File must exist for initial statSync
303
+ const readError = new Error('Simulated read error');
304
+ vi.spyOn(fsPromises, 'readFile').mockRejectedValueOnce(readError);
305
+
306
+ const result = await processSingleFileContent(
307
+ testTextFilePath,
308
+ tempRootDir,
309
+ new StandardFileSystemService(),
310
+ );
311
+ expect(result.error).toContain('Simulated read error');
312
+ expect(result.returnDisplay).toContain('Simulated read error');
313
+ });
314
+
315
+ it('should handle read errors for image/pdf files', async () => {
316
+ actualNodeFs.writeFileSync(testImageFilePath, 'content'); // File must exist
317
+ mockMimeLookup.mockReturnValue('image/png');
318
+ const readError = new Error('Simulated image read error');
319
+ vi.spyOn(fsPromises, 'readFile').mockRejectedValueOnce(readError);
320
+
321
+ const result = await processSingleFileContent(
322
+ testImageFilePath,
323
+ tempRootDir,
324
+ new StandardFileSystemService(),
325
+ );
326
+ expect(result.error).toContain('Simulated image read error');
327
+ expect(result.returnDisplay).toContain('Simulated image read error');
328
+ });
329
+
330
+ it('should process an image file', async () => {
331
+ const fakePngData = Buffer.from('fake png data');
332
+ actualNodeFs.writeFileSync(testImageFilePath, fakePngData);
333
+ mockMimeLookup.mockReturnValue('image/png');
334
+ const result = await processSingleFileContent(
335
+ testImageFilePath,
336
+ tempRootDir,
337
+ new StandardFileSystemService(),
338
+ );
339
+ expect(
340
+ (result.llmContent as { inlineData: unknown }).inlineData,
341
+ ).toBeDefined();
342
+ expect(
343
+ (result.llmContent as { inlineData: { mimeType: string } }).inlineData
344
+ .mimeType,
345
+ ).toBe('image/png');
346
+ expect(
347
+ (result.llmContent as { inlineData: { data: string } }).inlineData.data,
348
+ ).toBe(fakePngData.toString('base64'));
349
+ expect(result.returnDisplay).toContain('Read image file: image.png');
350
+ });
351
+
352
+ it('should process a PDF file', async () => {
353
+ const fakePdfData = Buffer.from('fake pdf data');
354
+ actualNodeFs.writeFileSync(testPdfFilePath, fakePdfData);
355
+ mockMimeLookup.mockReturnValue('application/pdf');
356
+ const result = await processSingleFileContent(
357
+ testPdfFilePath,
358
+ tempRootDir,
359
+ new StandardFileSystemService(),
360
+ );
361
+ expect(
362
+ (result.llmContent as { inlineData: unknown }).inlineData,
363
+ ).toBeDefined();
364
+ expect(
365
+ (result.llmContent as { inlineData: { mimeType: string } }).inlineData
366
+ .mimeType,
367
+ ).toBe('application/pdf');
368
+ expect(
369
+ (result.llmContent as { inlineData: { data: string } }).inlineData.data,
370
+ ).toBe(fakePdfData.toString('base64'));
371
+ expect(result.returnDisplay).toContain('Read pdf file: document.pdf');
372
+ });
373
+
374
+ it('should read an SVG file as text when under 1MB', async () => {
375
+ const svgContent = `
376
+ <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
377
+ <rect width="100" height="100" fill="blue" />
378
+ </svg>
379
+ `;
380
+ const testSvgFilePath = path.join(tempRootDir, 'test.svg');
381
+ actualNodeFs.writeFileSync(testSvgFilePath, svgContent, 'utf-8');
382
+
383
+ mockMimeLookup.mockReturnValue('image/svg+xml');
384
+
385
+ const result = await processSingleFileContent(
386
+ testSvgFilePath,
387
+ tempRootDir,
388
+ new StandardFileSystemService(),
389
+ );
390
+
391
+ expect(result.llmContent).toBe(svgContent);
392
+ expect(result.returnDisplay).toContain('Read SVG as text');
393
+ });
394
+
395
+ it('should skip binary files', async () => {
396
+ actualNodeFs.writeFileSync(
397
+ testBinaryFilePath,
398
+ Buffer.from([0x00, 0x01, 0x02]),
399
+ );
400
+ mockMimeLookup.mockReturnValueOnce('application/octet-stream');
401
+ // isBinaryFile will operate on the real file.
402
+
403
+ const result = await processSingleFileContent(
404
+ testBinaryFilePath,
405
+ tempRootDir,
406
+ new StandardFileSystemService(),
407
+ );
408
+ expect(result.llmContent).toContain(
409
+ 'Cannot display content of binary file',
410
+ );
411
+ expect(result.returnDisplay).toContain('Skipped binary file: app.exe');
412
+ });
413
+
414
+ it('should handle path being a directory', async () => {
415
+ const result = await processSingleFileContent(
416
+ directoryPath,
417
+ tempRootDir,
418
+ new StandardFileSystemService(),
419
+ );
420
+ expect(result.error).toContain('Path is a directory');
421
+ expect(result.returnDisplay).toContain('Path is a directory');
422
+ });
423
+
424
+ it('should paginate text files correctly (offset and limit)', async () => {
425
+ const lines = Array.from({ length: 20 }, (_, i) => `Line ${i + 1}`);
426
+ actualNodeFs.writeFileSync(testTextFilePath, lines.join('\n'));
427
+
428
+ const result = await processSingleFileContent(
429
+ testTextFilePath,
430
+ tempRootDir,
431
+ new StandardFileSystemService(),
432
+ 5,
433
+ 5,
434
+ ); // Read lines 6-10
435
+ const expectedContent = lines.slice(5, 10).join('\n');
436
+
437
+ expect(result.llmContent).toBe(expectedContent);
438
+ expect(result.returnDisplay).toBe('Read lines 6-10 of 20 from test.txt');
439
+ expect(result.isTruncated).toBe(true);
440
+ expect(result.originalLineCount).toBe(20);
441
+ expect(result.linesShown).toEqual([6, 10]);
442
+ });
443
+
444
+ it('should identify truncation when reading the end of a file', async () => {
445
+ const lines = Array.from({ length: 20 }, (_, i) => `Line ${i + 1}`);
446
+ actualNodeFs.writeFileSync(testTextFilePath, lines.join('\n'));
447
+
448
+ // Read from line 11 to 20. The start is not 0, so it's truncated.
449
+ const result = await processSingleFileContent(
450
+ testTextFilePath,
451
+ tempRootDir,
452
+ new StandardFileSystemService(),
453
+ 10,
454
+ 10,
455
+ );
456
+ const expectedContent = lines.slice(10, 20).join('\n');
457
+
458
+ expect(result.llmContent).toContain(expectedContent);
459
+ expect(result.returnDisplay).toBe('Read lines 11-20 of 20 from test.txt');
460
+ expect(result.isTruncated).toBe(true); // This is the key check for the bug
461
+ expect(result.originalLineCount).toBe(20);
462
+ expect(result.linesShown).toEqual([11, 20]);
463
+ });
464
+
465
+ it('should handle limit exceeding file length', async () => {
466
+ const lines = ['Line 1', 'Line 2'];
467
+ actualNodeFs.writeFileSync(testTextFilePath, lines.join('\n'));
468
+
469
+ const result = await processSingleFileContent(
470
+ testTextFilePath,
471
+ tempRootDir,
472
+ new StandardFileSystemService(),
473
+ 0,
474
+ 10,
475
+ );
476
+ const expectedContent = lines.join('\n');
477
+
478
+ expect(result.llmContent).toBe(expectedContent);
479
+ expect(result.returnDisplay).toBe('');
480
+ expect(result.isTruncated).toBe(false);
481
+ expect(result.originalLineCount).toBe(2);
482
+ expect(result.linesShown).toEqual([1, 2]);
483
+ });
484
+
485
+ it('should truncate long lines in text files', async () => {
486
+ const longLine = 'a'.repeat(2500);
487
+ actualNodeFs.writeFileSync(
488
+ testTextFilePath,
489
+ `Short line\n${longLine}\nAnother short line`,
490
+ );
491
+
492
+ const result = await processSingleFileContent(
493
+ testTextFilePath,
494
+ tempRootDir,
495
+ new StandardFileSystemService(),
496
+ );
497
+
498
+ expect(result.llmContent).toContain('Short line');
499
+ expect(result.llmContent).toContain(
500
+ longLine.substring(0, 2000) + '... [truncated]',
501
+ );
502
+ expect(result.llmContent).toContain('Another short line');
503
+ expect(result.returnDisplay).toBe(
504
+ 'Read all 3 lines from test.txt (some lines were shortened)',
505
+ );
506
+ expect(result.isTruncated).toBe(true);
507
+ });
508
+
509
+ it('should truncate when line count exceeds the limit', async () => {
510
+ const lines = Array.from({ length: 11 }, (_, i) => `Line ${i + 1}`);
511
+ actualNodeFs.writeFileSync(testTextFilePath, lines.join('\n'));
512
+
513
+ // Read 5 lines, but there are 11 total
514
+ const result = await processSingleFileContent(
515
+ testTextFilePath,
516
+ tempRootDir,
517
+ new StandardFileSystemService(),
518
+ 0,
519
+ 5,
520
+ );
521
+
522
+ expect(result.isTruncated).toBe(true);
523
+ expect(result.returnDisplay).toBe('Read lines 1-5 of 11 from test.txt');
524
+ });
525
+
526
+ it('should truncate when a line length exceeds the character limit', async () => {
527
+ const longLine = 'b'.repeat(2500);
528
+ const lines = Array.from({ length: 10 }, (_, i) => `Line ${i + 1}`);
529
+ lines.push(longLine); // Total 11 lines
530
+ actualNodeFs.writeFileSync(testTextFilePath, lines.join('\n'));
531
+
532
+ // Read all 11 lines, including the long one
533
+ const result = await processSingleFileContent(
534
+ testTextFilePath,
535
+ tempRootDir,
536
+ new StandardFileSystemService(),
537
+ 0,
538
+ 11,
539
+ );
540
+
541
+ expect(result.isTruncated).toBe(true);
542
+ expect(result.returnDisplay).toBe(
543
+ 'Read all 11 lines from test.txt (some lines were shortened)',
544
+ );
545
+ });
546
+
547
+ it('should truncate both line count and line length when both exceed limits', async () => {
548
+ const linesWithLongInMiddle = Array.from(
549
+ { length: 20 },
550
+ (_, i) => `Line ${i + 1}`,
551
+ );
552
+ linesWithLongInMiddle[4] = 'c'.repeat(2500);
553
+ actualNodeFs.writeFileSync(
554
+ testTextFilePath,
555
+ linesWithLongInMiddle.join('\n'),
556
+ );
557
+
558
+ // Read 10 lines out of 20, including the long line
559
+ const result = await processSingleFileContent(
560
+ testTextFilePath,
561
+ tempRootDir,
562
+ new StandardFileSystemService(),
563
+ 0,
564
+ 10,
565
+ );
566
+ expect(result.isTruncated).toBe(true);
567
+ expect(result.returnDisplay).toBe(
568
+ 'Read lines 1-10 of 20 from test.txt (some lines were shortened)',
569
+ );
570
+ });
571
+
572
+ it('should return an error if the file size exceeds 20MB', async () => {
573
+ // Create a file just over 20MB
574
+ const twentyOneMB = 21 * 1024 * 1024;
575
+ const buffer = Buffer.alloc(twentyOneMB, 0x61); // Fill with 'a'
576
+ actualNodeFs.writeFileSync(testTextFilePath, buffer);
577
+
578
+ const result = await processSingleFileContent(
579
+ testTextFilePath,
580
+ tempRootDir,
581
+ new StandardFileSystemService(),
582
+ );
583
+
584
+ expect(result.error).toContain('File size exceeds the 20MB limit');
585
+ expect(result.returnDisplay).toContain(
586
+ 'File size exceeds the 20MB limit',
587
+ );
588
+ expect(result.llmContent).toContain('File size exceeds the 20MB limit');
589
+ });
590
+ });
591
+ });
projects/ui/qwen-code/packages/core/src/utils/fileUtils.ts ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { PartUnion } from '@google/genai';
10
+ import mime from 'mime-types';
11
+ import { FileSystemService } from '../services/fileSystemService.js';
12
+
13
+ // Constants for text file processing
14
+ const DEFAULT_MAX_LINES_TEXT_FILE = 2000;
15
+ const MAX_LINE_LENGTH_TEXT_FILE = 2000;
16
+
17
+ // Default values for encoding and separator format
18
+ export const DEFAULT_ENCODING: BufferEncoding = 'utf-8';
19
+
20
+ /**
21
+ * Looks up the specific MIME type for a file path.
22
+ * @param filePath Path to the file.
23
+ * @returns The specific MIME type string (e.g., 'text/python', 'application/javascript') or undefined if not found or ambiguous.
24
+ */
25
+ export function getSpecificMimeType(filePath: string): string | undefined {
26
+ const lookedUpMime = mime.lookup(filePath);
27
+ return typeof lookedUpMime === 'string' ? lookedUpMime : undefined;
28
+ }
29
+
30
+ /**
31
+ * Checks if a path is within a given root directory.
32
+ * @param pathToCheck The absolute path to check.
33
+ * @param rootDirectory The absolute root directory.
34
+ * @returns True if the path is within the root directory, false otherwise.
35
+ */
36
+ export function isWithinRoot(
37
+ pathToCheck: string,
38
+ rootDirectory: string,
39
+ ): boolean {
40
+ const normalizedPathToCheck = path.resolve(pathToCheck);
41
+ const normalizedRootDirectory = path.resolve(rootDirectory);
42
+
43
+ // Ensure the rootDirectory path ends with a separator for correct startsWith comparison,
44
+ // unless it's the root path itself (e.g., '/' or 'C:\').
45
+ const rootWithSeparator =
46
+ normalizedRootDirectory === path.sep ||
47
+ normalizedRootDirectory.endsWith(path.sep)
48
+ ? normalizedRootDirectory
49
+ : normalizedRootDirectory + path.sep;
50
+
51
+ return (
52
+ normalizedPathToCheck === normalizedRootDirectory ||
53
+ normalizedPathToCheck.startsWith(rootWithSeparator)
54
+ );
55
+ }
56
+
57
+ /**
58
+ * Determines if a file is likely binary based on content sampling.
59
+ * @param filePath Path to the file.
60
+ * @returns Promise that resolves to true if the file appears to be binary.
61
+ */
62
+ export async function isBinaryFile(filePath: string): Promise<boolean> {
63
+ let fileHandle: fs.promises.FileHandle | undefined;
64
+ try {
65
+ fileHandle = await fs.promises.open(filePath, 'r');
66
+
67
+ // Read up to 4KB or file size, whichever is smaller
68
+ const stats = await fileHandle.stat();
69
+ const fileSize = stats.size;
70
+ if (fileSize === 0) {
71
+ // Empty file is not considered binary for content checking
72
+ return false;
73
+ }
74
+ const bufferSize = Math.min(4096, fileSize);
75
+ const buffer = Buffer.alloc(bufferSize);
76
+ const result = await fileHandle.read(buffer, 0, buffer.length, 0);
77
+ const bytesRead = result.bytesRead;
78
+
79
+ if (bytesRead === 0) return false;
80
+
81
+ let nonPrintableCount = 0;
82
+ for (let i = 0; i < bytesRead; i++) {
83
+ if (buffer[i] === 0) return true; // Null byte is a strong indicator
84
+ if (buffer[i] < 9 || (buffer[i] > 13 && buffer[i] < 32)) {
85
+ nonPrintableCount++;
86
+ }
87
+ }
88
+ // If >30% non-printable characters, consider it binary
89
+ return nonPrintableCount / bytesRead > 0.3;
90
+ } catch (error) {
91
+ // Log error for debugging while maintaining existing behavior
92
+ console.warn(
93
+ `Failed to check if file is binary: ${filePath}`,
94
+ error instanceof Error ? error.message : String(error),
95
+ );
96
+ // If any error occurs (e.g. file not found, permissions),
97
+ // treat as not binary here; let higher-level functions handle existence/access errors.
98
+ return false;
99
+ } finally {
100
+ // Safely close the file handle if it was successfully opened
101
+ if (fileHandle) {
102
+ try {
103
+ await fileHandle.close();
104
+ } catch (closeError) {
105
+ // Log close errors for debugging while continuing with cleanup
106
+ console.warn(
107
+ `Failed to close file handle for: ${filePath}`,
108
+ closeError instanceof Error ? closeError.message : String(closeError),
109
+ );
110
+ // The important thing is that we attempted to clean up
111
+ }
112
+ }
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Detects the type of file based on extension and content.
118
+ * @param filePath Path to the file.
119
+ * @returns Promise that resolves to 'text', 'image', 'pdf', 'audio', 'video', 'binary' or 'svg'.
120
+ */
121
+ export async function detectFileType(
122
+ filePath: string,
123
+ ): Promise<'text' | 'image' | 'pdf' | 'audio' | 'video' | 'binary' | 'svg'> {
124
+ const ext = path.extname(filePath).toLowerCase();
125
+
126
+ // The mimetype for various TypeScript extensions (ts, mts, cts, tsx) can be
127
+ // MPEG transport stream (a video format), but we want to assume these are
128
+ // TypeScript files instead.
129
+ if (['.ts', '.mts', '.cts'].includes(ext)) {
130
+ return 'text';
131
+ }
132
+
133
+ if (ext === '.svg') {
134
+ return 'svg';
135
+ }
136
+
137
+ const lookedUpMimeType = mime.lookup(filePath); // Returns false if not found, or the mime type string
138
+ if (lookedUpMimeType) {
139
+ if (lookedUpMimeType.startsWith('image/')) {
140
+ return 'image';
141
+ }
142
+ if (lookedUpMimeType.startsWith('audio/')) {
143
+ return 'audio';
144
+ }
145
+ if (lookedUpMimeType.startsWith('video/')) {
146
+ return 'video';
147
+ }
148
+ if (lookedUpMimeType === 'application/pdf') {
149
+ return 'pdf';
150
+ }
151
+ }
152
+
153
+ // Stricter binary check for common non-text extensions before content check
154
+ // These are often not well-covered by mime-types or might be misidentified.
155
+ if (
156
+ [
157
+ '.zip',
158
+ '.tar',
159
+ '.gz',
160
+ '.exe',
161
+ '.dll',
162
+ '.so',
163
+ '.class',
164
+ '.jar',
165
+ '.war',
166
+ '.7z',
167
+ '.doc',
168
+ '.docx',
169
+ '.xls',
170
+ '.xlsx',
171
+ '.ppt',
172
+ '.pptx',
173
+ '.odt',
174
+ '.ods',
175
+ '.odp',
176
+ '.bin',
177
+ '.dat',
178
+ '.obj',
179
+ '.o',
180
+ '.a',
181
+ '.lib',
182
+ '.wasm',
183
+ '.pyc',
184
+ '.pyo',
185
+ ].includes(ext)
186
+ ) {
187
+ return 'binary';
188
+ }
189
+
190
+ // Fall back to content-based check if mime type wasn't conclusive for image/pdf
191
+ // and it's not a known binary extension.
192
+ if (await isBinaryFile(filePath)) {
193
+ return 'binary';
194
+ }
195
+
196
+ return 'text';
197
+ }
198
+
199
+ export enum FileErrorType {
200
+ FILE_NOT_FOUND = 'FILE_NOT_FOUND',
201
+ IS_DIRECTORY = 'IS_DIRECTORY',
202
+ FILE_TOO_LARGE = 'FILE_TOO_LARGE',
203
+ READ_ERROR = 'READ_ERROR',
204
+ }
205
+
206
+ export interface ProcessedFileReadResult {
207
+ llmContent: PartUnion; // string for text, Part for image/pdf/unreadable binary
208
+ returnDisplay: string;
209
+ error?: string; // Optional error message for the LLM if file processing failed
210
+ errorType?: FileErrorType; // Structured error type using enum
211
+ isTruncated?: boolean; // For text files, indicates if content was truncated
212
+ originalLineCount?: number; // For text files
213
+ linesShown?: [number, number]; // For text files [startLine, endLine] (1-based for display)
214
+ }
215
+
216
+ /**
217
+ * Reads and processes a single file, handling text, images, and PDFs.
218
+ * @param filePath Absolute path to the file.
219
+ * @param rootDirectory Absolute path to the project root for relative path display.
220
+ * @param offset Optional offset for text files (0-based line number).
221
+ * @param limit Optional limit for text files (number of lines to read).
222
+ * @returns ProcessedFileReadResult object.
223
+ */
224
+ export async function processSingleFileContent(
225
+ filePath: string,
226
+ rootDirectory: string,
227
+ fileSystemService: FileSystemService,
228
+ offset?: number,
229
+ limit?: number,
230
+ ): Promise<ProcessedFileReadResult> {
231
+ try {
232
+ if (!fs.existsSync(filePath)) {
233
+ // Sync check is acceptable before async read
234
+ return {
235
+ llmContent: '',
236
+ returnDisplay: 'File not found.',
237
+ error: `File not found: ${filePath}`,
238
+ errorType: FileErrorType.FILE_NOT_FOUND,
239
+ };
240
+ }
241
+ const stats = await fs.promises.stat(filePath);
242
+ if (stats.isDirectory()) {
243
+ return {
244
+ llmContent: '',
245
+ returnDisplay: 'Path is a directory.',
246
+ error: `Path is a directory, not a file: ${filePath}`,
247
+ errorType: FileErrorType.IS_DIRECTORY,
248
+ };
249
+ }
250
+
251
+ const fileSizeInBytes = stats.size;
252
+ // 20MB limit
253
+ const maxFileSize = 20 * 1024 * 1024;
254
+
255
+ if (fileSizeInBytes > maxFileSize) {
256
+ throw new Error(
257
+ `File size exceeds the 20MB limit: ${filePath} (${(
258
+ fileSizeInBytes /
259
+ (1024 * 1024)
260
+ ).toFixed(2)}MB)`,
261
+ );
262
+ }
263
+
264
+ const fileType = await detectFileType(filePath);
265
+ const relativePathForDisplay = path
266
+ .relative(rootDirectory, filePath)
267
+ .replace(/\\/g, '/');
268
+
269
+ switch (fileType) {
270
+ case 'binary': {
271
+ return {
272
+ llmContent: `Cannot display content of binary file: ${relativePathForDisplay}`,
273
+ returnDisplay: `Skipped binary file: ${relativePathForDisplay}`,
274
+ };
275
+ }
276
+ case 'svg': {
277
+ const SVG_MAX_SIZE_BYTES = 1 * 1024 * 1024;
278
+ if (stats.size > SVG_MAX_SIZE_BYTES) {
279
+ return {
280
+ llmContent: `Cannot display content of SVG file larger than 1MB: ${relativePathForDisplay}`,
281
+ returnDisplay: `Skipped large SVG file (>1MB): ${relativePathForDisplay}`,
282
+ };
283
+ }
284
+ const content = await fileSystemService.readTextFile(filePath);
285
+ return {
286
+ llmContent: content,
287
+ returnDisplay: `Read SVG as text: ${relativePathForDisplay}`,
288
+ };
289
+ }
290
+ case 'text': {
291
+ const content = await fileSystemService.readTextFile(filePath);
292
+ const lines = content.split('\n');
293
+ const originalLineCount = lines.length;
294
+
295
+ const startLine = offset || 0;
296
+ const effectiveLimit =
297
+ limit === undefined ? DEFAULT_MAX_LINES_TEXT_FILE : limit;
298
+ // Ensure endLine does not exceed originalLineCount
299
+ const endLine = Math.min(startLine + effectiveLimit, originalLineCount);
300
+ // Ensure selectedLines doesn't try to slice beyond array bounds if startLine is too high
301
+ const actualStartLine = Math.min(startLine, originalLineCount);
302
+ const selectedLines = lines.slice(actualStartLine, endLine);
303
+
304
+ let linesWereTruncatedInLength = false;
305
+ const formattedLines = selectedLines.map((line) => {
306
+ if (line.length > MAX_LINE_LENGTH_TEXT_FILE) {
307
+ linesWereTruncatedInLength = true;
308
+ return (
309
+ line.substring(0, MAX_LINE_LENGTH_TEXT_FILE) + '... [truncated]'
310
+ );
311
+ }
312
+ return line;
313
+ });
314
+
315
+ const contentRangeTruncated =
316
+ startLine > 0 || endLine < originalLineCount;
317
+ const isTruncated = contentRangeTruncated || linesWereTruncatedInLength;
318
+ const llmContent = formattedLines.join('\n');
319
+
320
+ // By default, return nothing to streamline the common case of a successful read_file.
321
+ let returnDisplay = '';
322
+ if (contentRangeTruncated) {
323
+ returnDisplay = `Read lines ${
324
+ actualStartLine + 1
325
+ }-${endLine} of ${originalLineCount} from ${relativePathForDisplay}`;
326
+ if (linesWereTruncatedInLength) {
327
+ returnDisplay += ' (some lines were shortened)';
328
+ }
329
+ } else if (linesWereTruncatedInLength) {
330
+ returnDisplay = `Read all ${originalLineCount} lines from ${relativePathForDisplay} (some lines were shortened)`;
331
+ }
332
+
333
+ return {
334
+ llmContent,
335
+ returnDisplay,
336
+ isTruncated,
337
+ originalLineCount,
338
+ linesShown: [actualStartLine + 1, endLine],
339
+ };
340
+ }
341
+ case 'image':
342
+ case 'pdf':
343
+ case 'audio':
344
+ case 'video': {
345
+ const contentBuffer = await fs.promises.readFile(filePath);
346
+ const base64Data = contentBuffer.toString('base64');
347
+ return {
348
+ llmContent: {
349
+ inlineData: {
350
+ data: base64Data,
351
+ mimeType: mime.lookup(filePath) || 'application/octet-stream',
352
+ },
353
+ },
354
+ returnDisplay: `Read ${fileType} file: ${relativePathForDisplay}`,
355
+ };
356
+ }
357
+ default: {
358
+ // Should not happen with current detectFileType logic
359
+ const exhaustiveCheck: never = fileType;
360
+ return {
361
+ llmContent: `Unhandled file type: ${exhaustiveCheck}`,
362
+ returnDisplay: `Skipped unhandled file type: ${relativePathForDisplay}`,
363
+ error: `Unhandled file type for ${filePath}`,
364
+ };
365
+ }
366
+ }
367
+ } catch (error) {
368
+ const errorMessage = error instanceof Error ? error.message : String(error);
369
+ const displayPath = path
370
+ .relative(rootDirectory, filePath)
371
+ .replace(/\\/g, '/');
372
+ return {
373
+ llmContent: `Error reading file ${displayPath}: ${errorMessage}`,
374
+ returnDisplay: `Error reading file ${displayPath}: ${errorMessage}`,
375
+ error: `Error reading file ${filePath}: ${errorMessage}`,
376
+ };
377
+ }
378
+ }
projects/ui/qwen-code/packages/core/src/utils/flashFallback.integration.test.ts ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
8
+ import { Config } from '../config/config.js';
9
+ import fs from 'node:fs';
10
+ import {
11
+ setSimulate429,
12
+ disableSimulationAfterFallback,
13
+ shouldSimulate429,
14
+ createSimulated429Error,
15
+ resetRequestCounter,
16
+ } from './testUtils.js';
17
+ import { DEFAULT_GEMINI_FLASH_MODEL } from '../config/models.js';
18
+ import { retryWithBackoff } from './retry.js';
19
+ import { AuthType } from '../core/contentGenerator.js';
20
+
21
+ vi.mock('node:fs');
22
+
23
+ vi.mock('node:fs');
24
+
25
+ describe('Flash Fallback Integration', () => {
26
+ let config: Config;
27
+
28
+ beforeEach(() => {
29
+ vi.mocked(fs.existsSync).mockReturnValue(true);
30
+ vi.mocked(fs.statSync).mockReturnValue({
31
+ isDirectory: () => true,
32
+ } as fs.Stats);
33
+ config = new Config({
34
+ sessionId: 'test-session',
35
+ targetDir: '/test',
36
+ debugMode: false,
37
+ cwd: '/test',
38
+ model: 'gemini-2.5-pro',
39
+ });
40
+
41
+ // Reset simulation state for each test
42
+ setSimulate429(false);
43
+ resetRequestCounter();
44
+ });
45
+
46
+ it('should automatically accept fallback', async () => {
47
+ // Set up a minimal flash fallback handler for testing
48
+ const flashFallbackHandler = async (): Promise<boolean> => true;
49
+
50
+ config.setFlashFallbackHandler(flashFallbackHandler);
51
+
52
+ // Call the handler directly to test
53
+ const result = await config.flashFallbackHandler!(
54
+ 'gemini-2.5-pro',
55
+ DEFAULT_GEMINI_FLASH_MODEL,
56
+ );
57
+
58
+ // Verify it automatically accepts
59
+ expect(result).toBe(true);
60
+ });
61
+
62
+ it('should trigger fallback after 2 consecutive 429 errors for OAuth users', async () => {
63
+ let fallbackCalled = false;
64
+ let fallbackModel = '';
65
+
66
+ // Mock function that simulates exactly 2 429 errors, then succeeds after fallback
67
+ const mockApiCall = vi
68
+ .fn()
69
+ .mockRejectedValueOnce(createSimulated429Error())
70
+ .mockRejectedValueOnce(createSimulated429Error())
71
+ .mockResolvedValueOnce('success after fallback');
72
+
73
+ // Mock fallback handler
74
+ const mockFallbackHandler = vi.fn(async (_authType?: string) => {
75
+ fallbackCalled = true;
76
+ fallbackModel = DEFAULT_GEMINI_FLASH_MODEL;
77
+ return fallbackModel;
78
+ });
79
+
80
+ // Test with OAuth personal auth type, with maxAttempts = 2 to ensure fallback triggers
81
+ const result = await retryWithBackoff(mockApiCall, {
82
+ maxAttempts: 2,
83
+ initialDelayMs: 1,
84
+ maxDelayMs: 10,
85
+ shouldRetry: (error: Error) => {
86
+ const status = (error as Error & { status?: number }).status;
87
+ return status === 429;
88
+ },
89
+ onPersistent429: mockFallbackHandler,
90
+ authType: AuthType.LOGIN_WITH_GOOGLE,
91
+ });
92
+
93
+ // Verify fallback was triggered
94
+ expect(fallbackCalled).toBe(true);
95
+ expect(fallbackModel).toBe(DEFAULT_GEMINI_FLASH_MODEL);
96
+ expect(mockFallbackHandler).toHaveBeenCalledWith(
97
+ AuthType.LOGIN_WITH_GOOGLE,
98
+ expect.any(Error),
99
+ );
100
+ expect(result).toBe('success after fallback');
101
+ // Should have: 2 failures, then fallback triggered, then 1 success after retry reset
102
+ expect(mockApiCall).toHaveBeenCalledTimes(3);
103
+ });
104
+
105
+ it('should not trigger fallback for API key users', async () => {
106
+ let fallbackCalled = false;
107
+
108
+ // Mock function that simulates 429 errors
109
+ const mockApiCall = vi.fn().mockRejectedValue(createSimulated429Error());
110
+
111
+ // Mock fallback handler
112
+ const mockFallbackHandler = vi.fn(async () => {
113
+ fallbackCalled = true;
114
+ return DEFAULT_GEMINI_FLASH_MODEL;
115
+ });
116
+
117
+ // Test with API key auth type - should not trigger fallback
118
+ try {
119
+ await retryWithBackoff(mockApiCall, {
120
+ maxAttempts: 5,
121
+ initialDelayMs: 10,
122
+ maxDelayMs: 100,
123
+ shouldRetry: (error: Error) => {
124
+ const status = (error as Error & { status?: number }).status;
125
+ return status === 429;
126
+ },
127
+ onPersistent429: mockFallbackHandler,
128
+ authType: AuthType.USE_GEMINI, // API key auth type
129
+ });
130
+ } catch (error) {
131
+ // Expected to throw after max attempts
132
+ expect((error as Error).message).toContain('Rate limit exceeded');
133
+ }
134
+
135
+ // Verify fallback was NOT triggered for API key users
136
+ expect(fallbackCalled).toBe(false);
137
+ expect(mockFallbackHandler).not.toHaveBeenCalled();
138
+ });
139
+
140
+ it('should properly disable simulation state after fallback', () => {
141
+ // Enable simulation
142
+ setSimulate429(true);
143
+
144
+ // Verify simulation is enabled
145
+ expect(shouldSimulate429()).toBe(true);
146
+
147
+ // Disable simulation after fallback
148
+ disableSimulationAfterFallback();
149
+
150
+ // Verify simulation is now disabled
151
+ expect(shouldSimulate429()).toBe(false);
152
+ });
153
+ });
projects/ui/qwen-code/packages/core/src/utils/formatters.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ export const formatMemoryUsage = (bytes: number): string => {
8
+ const gb = bytes / (1024 * 1024 * 1024);
9
+ if (bytes < 1024 * 1024) {
10
+ return `${(bytes / 1024).toFixed(1)} KB`;
11
+ }
12
+ if (bytes < 1024 * 1024 * 1024) {
13
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
14
+ }
15
+ return `${gb.toFixed(2)} GB`;
16
+ };
projects/ui/qwen-code/packages/core/src/utils/generateContentResponseUtilities.test.ts ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import {
9
+ getResponseText,
10
+ getResponseTextFromParts,
11
+ getFunctionCalls,
12
+ getFunctionCallsFromParts,
13
+ getFunctionCallsAsJson,
14
+ getFunctionCallsFromPartsAsJson,
15
+ getStructuredResponse,
16
+ getStructuredResponseFromParts,
17
+ } from './generateContentResponseUtilities.js';
18
+ import {
19
+ GenerateContentResponse,
20
+ Part,
21
+ FinishReason,
22
+ SafetyRating,
23
+ } from '@google/genai';
24
+
25
+ const mockTextPart = (text: string): Part => ({ text });
26
+ const mockFunctionCallPart = (
27
+ name: string,
28
+ args?: Record<string, unknown>,
29
+ ): Part => ({
30
+ functionCall: { name, args: args ?? {} },
31
+ });
32
+
33
+ const mockResponse = (
34
+ parts: Part[],
35
+ finishReason: FinishReason = FinishReason.STOP,
36
+ safetyRatings: SafetyRating[] = [],
37
+ ): GenerateContentResponse => ({
38
+ candidates: [
39
+ {
40
+ content: {
41
+ parts,
42
+ role: 'model',
43
+ },
44
+ index: 0,
45
+ finishReason,
46
+ safetyRatings,
47
+ },
48
+ ],
49
+ promptFeedback: {
50
+ safetyRatings: [],
51
+ },
52
+ text: undefined,
53
+ data: undefined,
54
+ functionCalls: undefined,
55
+ executableCode: undefined,
56
+ codeExecutionResult: undefined,
57
+ });
58
+
59
+ const minimalMockResponse = (
60
+ candidates: GenerateContentResponse['candidates'],
61
+ ): GenerateContentResponse => ({
62
+ candidates,
63
+ promptFeedback: { safetyRatings: [] },
64
+ text: undefined,
65
+ data: undefined,
66
+ functionCalls: undefined,
67
+ executableCode: undefined,
68
+ codeExecutionResult: undefined,
69
+ });
70
+
71
+ describe('generateContentResponseUtilities', () => {
72
+ describe('getResponseText', () => {
73
+ it('should return undefined for no candidates', () => {
74
+ expect(getResponseText(minimalMockResponse(undefined))).toBeUndefined();
75
+ });
76
+ it('should return undefined for empty candidates array', () => {
77
+ expect(getResponseText(minimalMockResponse([]))).toBeUndefined();
78
+ });
79
+ it('should return undefined for no parts', () => {
80
+ const response = mockResponse([]);
81
+ expect(getResponseText(response)).toBeUndefined();
82
+ });
83
+ it('should extract text from a single text part', () => {
84
+ const response = mockResponse([mockTextPart('Hello')]);
85
+ expect(getResponseText(response)).toBe('Hello');
86
+ });
87
+ it('should concatenate text from multiple text parts', () => {
88
+ const response = mockResponse([
89
+ mockTextPart('Hello '),
90
+ mockTextPart('World'),
91
+ ]);
92
+ expect(getResponseText(response)).toBe('Hello World');
93
+ });
94
+ it('should ignore function call parts', () => {
95
+ const response = mockResponse([
96
+ mockTextPart('Hello '),
97
+ mockFunctionCallPart('testFunc'),
98
+ mockTextPart('World'),
99
+ ]);
100
+ expect(getResponseText(response)).toBe('Hello World');
101
+ });
102
+ it('should return undefined if only function call parts exist', () => {
103
+ const response = mockResponse([
104
+ mockFunctionCallPart('testFunc'),
105
+ mockFunctionCallPart('anotherFunc'),
106
+ ]);
107
+ expect(getResponseText(response)).toBeUndefined();
108
+ });
109
+ });
110
+
111
+ describe('getResponseTextFromParts', () => {
112
+ it('should return undefined for no parts', () => {
113
+ expect(getResponseTextFromParts([])).toBeUndefined();
114
+ });
115
+ it('should extract text from a single text part', () => {
116
+ expect(getResponseTextFromParts([mockTextPart('Hello')])).toBe('Hello');
117
+ });
118
+ it('should concatenate text from multiple text parts', () => {
119
+ expect(
120
+ getResponseTextFromParts([
121
+ mockTextPart('Hello '),
122
+ mockTextPart('World'),
123
+ ]),
124
+ ).toBe('Hello World');
125
+ });
126
+ it('should ignore function call parts', () => {
127
+ expect(
128
+ getResponseTextFromParts([
129
+ mockTextPart('Hello '),
130
+ mockFunctionCallPart('testFunc'),
131
+ mockTextPart('World'),
132
+ ]),
133
+ ).toBe('Hello World');
134
+ });
135
+ it('should return undefined if only function call parts exist', () => {
136
+ expect(
137
+ getResponseTextFromParts([
138
+ mockFunctionCallPart('testFunc'),
139
+ mockFunctionCallPart('anotherFunc'),
140
+ ]),
141
+ ).toBeUndefined();
142
+ });
143
+ });
144
+
145
+ describe('getFunctionCalls', () => {
146
+ it('should return undefined for no candidates', () => {
147
+ expect(getFunctionCalls(minimalMockResponse(undefined))).toBeUndefined();
148
+ });
149
+ it('should return undefined for empty candidates array', () => {
150
+ expect(getFunctionCalls(minimalMockResponse([]))).toBeUndefined();
151
+ });
152
+ it('should return undefined for no parts', () => {
153
+ const response = mockResponse([]);
154
+ expect(getFunctionCalls(response)).toBeUndefined();
155
+ });
156
+ it('should extract a single function call', () => {
157
+ const func = { name: 'testFunc', args: { a: 1 } };
158
+ const response = mockResponse([
159
+ mockFunctionCallPart(func.name, func.args),
160
+ ]);
161
+ expect(getFunctionCalls(response)).toEqual([func]);
162
+ });
163
+ it('should extract multiple function calls', () => {
164
+ const func1 = { name: 'testFunc1', args: { a: 1 } };
165
+ const func2 = { name: 'testFunc2', args: { b: 2 } };
166
+ const response = mockResponse([
167
+ mockFunctionCallPart(func1.name, func1.args),
168
+ mockFunctionCallPart(func2.name, func2.args),
169
+ ]);
170
+ expect(getFunctionCalls(response)).toEqual([func1, func2]);
171
+ });
172
+ it('should ignore text parts', () => {
173
+ const func = { name: 'testFunc', args: { a: 1 } };
174
+ const response = mockResponse([
175
+ mockTextPart('Some text'),
176
+ mockFunctionCallPart(func.name, func.args),
177
+ mockTextPart('More text'),
178
+ ]);
179
+ expect(getFunctionCalls(response)).toEqual([func]);
180
+ });
181
+ it('should return undefined if only text parts exist', () => {
182
+ const response = mockResponse([
183
+ mockTextPart('Some text'),
184
+ mockTextPart('More text'),
185
+ ]);
186
+ expect(getFunctionCalls(response)).toBeUndefined();
187
+ });
188
+ });
189
+
190
+ describe('getFunctionCallsFromParts', () => {
191
+ it('should return undefined for no parts', () => {
192
+ expect(getFunctionCallsFromParts([])).toBeUndefined();
193
+ });
194
+ it('should extract a single function call', () => {
195
+ const func = { name: 'testFunc', args: { a: 1 } };
196
+ expect(
197
+ getFunctionCallsFromParts([mockFunctionCallPart(func.name, func.args)]),
198
+ ).toEqual([func]);
199
+ });
200
+ it('should extract multiple function calls', () => {
201
+ const func1 = { name: 'testFunc1', args: { a: 1 } };
202
+ const func2 = { name: 'testFunc2', args: { b: 2 } };
203
+ expect(
204
+ getFunctionCallsFromParts([
205
+ mockFunctionCallPart(func1.name, func1.args),
206
+ mockFunctionCallPart(func2.name, func2.args),
207
+ ]),
208
+ ).toEqual([func1, func2]);
209
+ });
210
+ it('should ignore text parts', () => {
211
+ const func = { name: 'testFunc', args: { a: 1 } };
212
+ expect(
213
+ getFunctionCallsFromParts([
214
+ mockTextPart('Some text'),
215
+ mockFunctionCallPart(func.name, func.args),
216
+ mockTextPart('More text'),
217
+ ]),
218
+ ).toEqual([func]);
219
+ });
220
+ it('should return undefined if only text parts exist', () => {
221
+ expect(
222
+ getFunctionCallsFromParts([
223
+ mockTextPart('Some text'),
224
+ mockTextPart('More text'),
225
+ ]),
226
+ ).toBeUndefined();
227
+ });
228
+ });
229
+
230
+ describe('getFunctionCallsAsJson', () => {
231
+ it('should return JSON string of function calls', () => {
232
+ const func1 = { name: 'testFunc1', args: { a: 1 } };
233
+ const func2 = { name: 'testFunc2', args: { b: 2 } };
234
+ const response = mockResponse([
235
+ mockFunctionCallPart(func1.name, func1.args),
236
+ mockTextPart('text in between'),
237
+ mockFunctionCallPart(func2.name, func2.args),
238
+ ]);
239
+ const expectedJson = JSON.stringify([func1, func2], null, 2);
240
+ expect(getFunctionCallsAsJson(response)).toBe(expectedJson);
241
+ });
242
+ it('should return undefined if no function calls', () => {
243
+ const response = mockResponse([mockTextPart('Hello')]);
244
+ expect(getFunctionCallsAsJson(response)).toBeUndefined();
245
+ });
246
+ });
247
+
248
+ describe('getFunctionCallsFromPartsAsJson', () => {
249
+ it('should return JSON string of function calls from parts', () => {
250
+ const func1 = { name: 'testFunc1', args: { a: 1 } };
251
+ const func2 = { name: 'testFunc2', args: { b: 2 } };
252
+ const parts = [
253
+ mockFunctionCallPart(func1.name, func1.args),
254
+ mockTextPart('text in between'),
255
+ mockFunctionCallPart(func2.name, func2.args),
256
+ ];
257
+ const expectedJson = JSON.stringify([func1, func2], null, 2);
258
+ expect(getFunctionCallsFromPartsAsJson(parts)).toBe(expectedJson);
259
+ });
260
+ it('should return undefined if no function calls in parts', () => {
261
+ const parts = [mockTextPart('Hello')];
262
+ expect(getFunctionCallsFromPartsAsJson(parts)).toBeUndefined();
263
+ });
264
+ });
265
+
266
+ describe('getStructuredResponse', () => {
267
+ it('should return only text if only text exists', () => {
268
+ const response = mockResponse([mockTextPart('Hello World')]);
269
+ expect(getStructuredResponse(response)).toBe('Hello World');
270
+ });
271
+ it('should return only function call JSON if only function calls exist', () => {
272
+ const func = { name: 'testFunc', args: { data: 'payload' } };
273
+ const response = mockResponse([
274
+ mockFunctionCallPart(func.name, func.args),
275
+ ]);
276
+ const expectedJson = JSON.stringify([func], null, 2);
277
+ expect(getStructuredResponse(response)).toBe(expectedJson);
278
+ });
279
+ it('should return text and function call JSON if both exist', () => {
280
+ const text = 'Consider this data:';
281
+ const func = { name: 'processData', args: { item: 42 } };
282
+ const response = mockResponse([
283
+ mockTextPart(text),
284
+ mockFunctionCallPart(func.name, func.args),
285
+ ]);
286
+ const expectedJson = JSON.stringify([func], null, 2);
287
+ expect(getStructuredResponse(response)).toBe(`${text}\n${expectedJson}`);
288
+ });
289
+ it('should return undefined if neither text nor function calls exist', () => {
290
+ const response = mockResponse([]);
291
+ expect(getStructuredResponse(response)).toBeUndefined();
292
+ });
293
+ });
294
+
295
+ describe('getStructuredResponseFromParts', () => {
296
+ it('should return only text if only text exists in parts', () => {
297
+ const parts = [mockTextPart('Hello World')];
298
+ expect(getStructuredResponseFromParts(parts)).toBe('Hello World');
299
+ });
300
+ it('should return only function call JSON if only function calls exist in parts', () => {
301
+ const func = { name: 'testFunc', args: { data: 'payload' } };
302
+ const parts = [mockFunctionCallPart(func.name, func.args)];
303
+ const expectedJson = JSON.stringify([func], null, 2);
304
+ expect(getStructuredResponseFromParts(parts)).toBe(expectedJson);
305
+ });
306
+ it('should return text and function call JSON if both exist in parts', () => {
307
+ const text = 'Consider this data:';
308
+ const func = { name: 'processData', args: { item: 42 } };
309
+ const parts = [
310
+ mockTextPart(text),
311
+ mockFunctionCallPart(func.name, func.args),
312
+ ];
313
+ const expectedJson = JSON.stringify([func], null, 2);
314
+ expect(getStructuredResponseFromParts(parts)).toBe(
315
+ `${text}\n${expectedJson}`,
316
+ );
317
+ });
318
+ it('should return undefined if neither text nor function calls exist in parts', () => {
319
+ const parts: Part[] = [];
320
+ expect(getStructuredResponseFromParts(parts)).toBeUndefined();
321
+ });
322
+ });
323
+ });
projects/ui/qwen-code/packages/core/src/utils/generateContentResponseUtilities.ts ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { GenerateContentResponse, Part, FunctionCall } from '@google/genai';
8
+
9
+ export function getResponseText(
10
+ response: GenerateContentResponse,
11
+ ): string | undefined {
12
+ const parts = response.candidates?.[0]?.content?.parts;
13
+ if (!parts) {
14
+ return undefined;
15
+ }
16
+ const textSegments = parts
17
+ .map((part) => part.text)
18
+ .filter((text): text is string => typeof text === 'string');
19
+
20
+ if (textSegments.length === 0) {
21
+ return undefined;
22
+ }
23
+ return textSegments.join('');
24
+ }
25
+
26
+ export function getResponseTextFromParts(parts: Part[]): string | undefined {
27
+ if (!parts) {
28
+ return undefined;
29
+ }
30
+ const textSegments = parts
31
+ .map((part) => part.text)
32
+ .filter((text): text is string => typeof text === 'string');
33
+
34
+ if (textSegments.length === 0) {
35
+ return undefined;
36
+ }
37
+ return textSegments.join('');
38
+ }
39
+
40
+ export function getFunctionCalls(
41
+ response: GenerateContentResponse,
42
+ ): FunctionCall[] | undefined {
43
+ const parts = response.candidates?.[0]?.content?.parts;
44
+ if (!parts) {
45
+ return undefined;
46
+ }
47
+ const functionCallParts = parts
48
+ .filter((part) => !!part.functionCall)
49
+ .map((part) => part.functionCall as FunctionCall);
50
+ return functionCallParts.length > 0 ? functionCallParts : undefined;
51
+ }
52
+
53
+ export function getFunctionCallsFromParts(
54
+ parts: Part[],
55
+ ): FunctionCall[] | undefined {
56
+ if (!parts) {
57
+ return undefined;
58
+ }
59
+ const functionCallParts = parts
60
+ .filter((part) => !!part.functionCall)
61
+ .map((part) => part.functionCall as FunctionCall);
62
+ return functionCallParts.length > 0 ? functionCallParts : undefined;
63
+ }
64
+
65
+ export function getFunctionCallsAsJson(
66
+ response: GenerateContentResponse,
67
+ ): string | undefined {
68
+ const functionCalls = getFunctionCalls(response);
69
+ if (!functionCalls) {
70
+ return undefined;
71
+ }
72
+ return JSON.stringify(functionCalls, null, 2);
73
+ }
74
+
75
+ export function getFunctionCallsFromPartsAsJson(
76
+ parts: Part[],
77
+ ): string | undefined {
78
+ const functionCalls = getFunctionCallsFromParts(parts);
79
+ if (!functionCalls) {
80
+ return undefined;
81
+ }
82
+ return JSON.stringify(functionCalls, null, 2);
83
+ }
84
+
85
+ export function getStructuredResponse(
86
+ response: GenerateContentResponse,
87
+ ): string | undefined {
88
+ const textContent = getResponseText(response);
89
+ const functionCallsJson = getFunctionCallsAsJson(response);
90
+
91
+ if (textContent && functionCallsJson) {
92
+ return `${textContent}\n${functionCallsJson}`;
93
+ }
94
+ if (textContent) {
95
+ return textContent;
96
+ }
97
+ if (functionCallsJson) {
98
+ return functionCallsJson;
99
+ }
100
+ return undefined;
101
+ }
102
+
103
+ export function getStructuredResponseFromParts(
104
+ parts: Part[],
105
+ ): string | undefined {
106
+ const textContent = getResponseTextFromParts(parts);
107
+ const functionCallsJson = getFunctionCallsFromPartsAsJson(parts);
108
+
109
+ if (textContent && functionCallsJson) {
110
+ return `${textContent}\n${functionCallsJson}`;
111
+ }
112
+ if (textContent) {
113
+ return textContent;
114
+ }
115
+ if (functionCallsJson) {
116
+ return functionCallsJson;
117
+ }
118
+ return undefined;
119
+ }
projects/ui/qwen-code/packages/core/src/utils/getFolderStructure.test.ts ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import fsPromises from 'fs/promises';
9
+ import * as nodePath from 'path';
10
+ import * as os from 'os';
11
+ import { getFolderStructure } from './getFolderStructure.js';
12
+ import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
13
+ import * as path from 'path';
14
+
15
+ describe('getFolderStructure', () => {
16
+ let testRootDir: string;
17
+
18
+ async function createEmptyDir(...pathSegments: string[]) {
19
+ const fullPath = path.join(testRootDir, ...pathSegments);
20
+ await fsPromises.mkdir(fullPath, { recursive: true });
21
+ }
22
+
23
+ async function createTestFile(...pathSegments: string[]) {
24
+ const fullPath = path.join(testRootDir, ...pathSegments);
25
+ await fsPromises.mkdir(path.dirname(fullPath), { recursive: true });
26
+ await fsPromises.writeFile(fullPath, '');
27
+ return fullPath;
28
+ }
29
+
30
+ beforeEach(async () => {
31
+ testRootDir = await fsPromises.mkdtemp(
32
+ path.join(os.tmpdir(), 'folder-structure-test-'),
33
+ );
34
+ });
35
+
36
+ afterEach(async () => {
37
+ await fsPromises.rm(testRootDir, { recursive: true, force: true });
38
+ });
39
+
40
+ it('should return basic folder structure', async () => {
41
+ await createTestFile('fileA1.ts');
42
+ await createTestFile('fileA2.js');
43
+ await createTestFile('subfolderB', 'fileB1.md');
44
+
45
+ const structure = await getFolderStructure(testRootDir);
46
+ expect(structure.trim()).toBe(
47
+ `
48
+ Showing up to 20 items (files + folders).
49
+
50
+ ${testRootDir}${path.sep}
51
+ ├───fileA1.ts
52
+ ├───fileA2.js
53
+ └───subfolderB${path.sep}
54
+ └───fileB1.md
55
+ `.trim(),
56
+ );
57
+ });
58
+
59
+ it('should handle an empty folder', async () => {
60
+ const structure = await getFolderStructure(testRootDir);
61
+ expect(structure.trim()).toBe(
62
+ `
63
+ Showing up to 20 items (files + folders).
64
+
65
+ ${testRootDir}${path.sep}
66
+ `
67
+ .trim()
68
+ .trim(),
69
+ );
70
+ });
71
+
72
+ it('should ignore folders specified in ignoredFolders (default)', async () => {
73
+ await createTestFile('.hiddenfile');
74
+ await createTestFile('file1.txt');
75
+ await createEmptyDir('emptyFolder');
76
+ await createTestFile('node_modules', 'somepackage', 'index.js');
77
+ await createTestFile('subfolderA', 'fileA1.ts');
78
+ await createTestFile('subfolderA', 'fileA2.js');
79
+ await createTestFile('subfolderA', 'subfolderB', 'fileB1.md');
80
+
81
+ const structure = await getFolderStructure(testRootDir);
82
+ expect(structure.trim()).toBe(
83
+ `
84
+ Showing up to 20 items (files + folders). Folders or files indicated with ... contain more items not shown, were ignored, or the display limit (20 items) was reached.
85
+
86
+ ${testRootDir}${path.sep}
87
+ ├───.hiddenfile
88
+ ├───file1.txt
89
+ ├───emptyFolder${path.sep}
90
+ ├───node_modules${path.sep}...
91
+ └───subfolderA${path.sep}
92
+ ├───fileA1.ts
93
+ ├───fileA2.js
94
+ └───subfolderB${path.sep}
95
+ └───fileB1.md
96
+ `.trim(),
97
+ );
98
+ });
99
+
100
+ it('should ignore folders specified in custom ignoredFolders', async () => {
101
+ await createTestFile('.hiddenfile');
102
+ await createTestFile('file1.txt');
103
+ await createEmptyDir('emptyFolder');
104
+ await createTestFile('node_modules', 'somepackage', 'index.js');
105
+ await createTestFile('subfolderA', 'fileA1.ts');
106
+
107
+ const structure = await getFolderStructure(testRootDir, {
108
+ ignoredFolders: new Set(['subfolderA', 'node_modules']),
109
+ });
110
+ const expected = `
111
+ Showing up to 20 items (files + folders). Folders or files indicated with ... contain more items not shown, were ignored, or the display limit (20 items) was reached.
112
+
113
+ ${testRootDir}${path.sep}
114
+ ├───.hiddenfile
115
+ ├───file1.txt
116
+ ├───emptyFolder${path.sep}
117
+ ├───node_modules${path.sep}...
118
+ └───subfolderA${path.sep}...
119
+ `.trim();
120
+ expect(structure.trim()).toBe(expected);
121
+ });
122
+
123
+ it('should filter files by fileIncludePattern', async () => {
124
+ await createTestFile('fileA1.ts');
125
+ await createTestFile('fileA2.js');
126
+ await createTestFile('subfolderB', 'fileB1.md');
127
+
128
+ const structure = await getFolderStructure(testRootDir, {
129
+ fileIncludePattern: /\.ts$/,
130
+ });
131
+ const expected = `
132
+ Showing up to 20 items (files + folders).
133
+
134
+ ${testRootDir}${path.sep}
135
+ ├───fileA1.ts
136
+ └───subfolderB${path.sep}
137
+ `.trim();
138
+ expect(structure.trim()).toBe(expected);
139
+ });
140
+
141
+ it('should handle maxItems truncation for files within a folder', async () => {
142
+ await createTestFile('fileA1.ts');
143
+ await createTestFile('fileA2.js');
144
+ await createTestFile('subfolderB', 'fileB1.md');
145
+
146
+ const structure = await getFolderStructure(testRootDir, {
147
+ maxItems: 3,
148
+ });
149
+ const expected = `
150
+ Showing up to 3 items (files + folders).
151
+
152
+ ${testRootDir}${path.sep}
153
+ ├───fileA1.ts
154
+ ├───fileA2.js
155
+ └───subfolderB${path.sep}
156
+ `.trim();
157
+ expect(structure.trim()).toBe(expected);
158
+ });
159
+
160
+ it('should handle maxItems truncation for subfolders', async () => {
161
+ for (let i = 0; i < 5; i++) {
162
+ await createTestFile(`folder-${i}`, 'child.txt');
163
+ }
164
+
165
+ const structure = await getFolderStructure(testRootDir, {
166
+ maxItems: 4,
167
+ });
168
+ const expectedRevised = `
169
+ Showing up to 4 items (files + folders). Folders or files indicated with ... contain more items not shown, were ignored, or the display limit (4 items) was reached.
170
+
171
+ ${testRootDir}${path.sep}
172
+ ├───folder-0${path.sep}
173
+ ├───folder-1${path.sep}
174
+ ├───folder-2${path.sep}
175
+ ├───folder-3${path.sep}
176
+ └───...
177
+ `.trim();
178
+ expect(structure.trim()).toBe(expectedRevised);
179
+ });
180
+
181
+ it('should handle maxItems that only allows the root folder itself', async () => {
182
+ await createTestFile('fileA1.ts');
183
+ await createTestFile('fileA2.ts');
184
+ await createTestFile('subfolderB', 'fileB1.ts');
185
+
186
+ const structure = await getFolderStructure(testRootDir, {
187
+ maxItems: 1,
188
+ });
189
+ const expected = `
190
+ Showing up to 1 items (files + folders). Folders or files indicated with ... contain more items not shown, were ignored, or the display limit (1 items) was reached.
191
+
192
+ ${testRootDir}${path.sep}
193
+ ├───fileA1.ts
194
+ ├───...
195
+ └───...
196
+ `.trim();
197
+ expect(structure.trim()).toBe(expected);
198
+ });
199
+
200
+ it('should handle non-existent directory', async () => {
201
+ const nonExistentPath = path.join(testRootDir, 'non-existent');
202
+ const structure = await getFolderStructure(nonExistentPath);
203
+ expect(structure).toContain(
204
+ `Error: Could not read directory "${nonExistentPath}". Check path and permissions.`,
205
+ );
206
+ });
207
+
208
+ it('should handle deep folder structure within limits', async () => {
209
+ await createTestFile('level1', 'level2', 'level3', 'file.txt');
210
+
211
+ const structure = await getFolderStructure(testRootDir, {
212
+ maxItems: 10,
213
+ });
214
+ const expected = `
215
+ Showing up to 10 items (files + folders).
216
+
217
+ ${testRootDir}${path.sep}
218
+ └───level1${path.sep}
219
+ └───level2${path.sep}
220
+ └───level3${path.sep}
221
+ └───file.txt
222
+ `.trim();
223
+ expect(structure.trim()).toBe(expected);
224
+ });
225
+
226
+ it('should truncate deep folder structure if maxItems is small', async () => {
227
+ await createTestFile('level1', 'level2', 'level3', 'file.txt');
228
+
229
+ const structure = await getFolderStructure(testRootDir, {
230
+ maxItems: 3,
231
+ });
232
+ const expected = `
233
+ Showing up to 3 items (files + folders).
234
+
235
+ ${testRootDir}${path.sep}
236
+ └───level1${path.sep}
237
+ └───level2${path.sep}
238
+ └───level3${path.sep}
239
+ `.trim();
240
+ expect(structure.trim()).toBe(expected);
241
+ });
242
+
243
+ describe('with gitignore', () => {
244
+ beforeEach(async () => {
245
+ await fsPromises.mkdir(path.join(testRootDir, '.git'), {
246
+ recursive: true,
247
+ });
248
+ });
249
+
250
+ it('should ignore files and folders specified in .gitignore', async () => {
251
+ await fsPromises.writeFile(
252
+ nodePath.join(testRootDir, '.gitignore'),
253
+ 'ignored.txt\nnode_modules/\n.gemini/*\n!/.gemini/config.yaml',
254
+ );
255
+ await createTestFile('file1.txt');
256
+ await createTestFile('node_modules', 'some-package', 'index.js');
257
+ await createTestFile('ignored.txt');
258
+ await createTestFile('.gemini', 'config.yaml');
259
+ await createTestFile('.gemini', 'logs.json');
260
+
261
+ const fileService = new FileDiscoveryService(testRootDir);
262
+ const structure = await getFolderStructure(testRootDir, {
263
+ fileService,
264
+ });
265
+
266
+ expect(structure).not.toContain('ignored.txt');
267
+ expect(structure).toContain(`node_modules${path.sep}...`);
268
+ expect(structure).not.toContain('logs.json');
269
+ expect(structure).toContain('config.yaml');
270
+ expect(structure).toContain('file1.txt');
271
+ });
272
+
273
+ it('should not ignore files if respectGitIgnore is false', async () => {
274
+ await fsPromises.writeFile(
275
+ nodePath.join(testRootDir, '.gitignore'),
276
+ 'ignored.txt',
277
+ );
278
+ await createTestFile('file1.txt');
279
+ await createTestFile('ignored.txt');
280
+
281
+ const fileService = new FileDiscoveryService(testRootDir);
282
+ const structure = await getFolderStructure(testRootDir, {
283
+ fileService,
284
+ fileFilteringOptions: {
285
+ respectGeminiIgnore: false,
286
+ respectGitIgnore: false,
287
+ },
288
+ });
289
+
290
+ expect(structure).toContain('ignored.txt');
291
+ expect(structure).toContain('file1.txt');
292
+ });
293
+ });
294
+
295
+ describe('with geminiignore', () => {
296
+ it('should ignore geminiignore files by default', async () => {
297
+ await fsPromises.writeFile(
298
+ nodePath.join(testRootDir, '.geminiignore'),
299
+ 'ignored.txt\nnode_modules/\n.gemini/\n!/.gemini/config.yaml',
300
+ );
301
+ await createTestFile('file1.txt');
302
+ await createTestFile('node_modules', 'some-package', 'index.js');
303
+ await createTestFile('ignored.txt');
304
+ await createTestFile('.gemini', 'config.yaml');
305
+ await createTestFile('.gemini', 'logs.json');
306
+
307
+ const fileService = new FileDiscoveryService(testRootDir);
308
+ const structure = await getFolderStructure(testRootDir, {
309
+ fileService,
310
+ });
311
+ expect(structure).not.toContain('ignored.txt');
312
+ expect(structure).toContain(`node_modules${path.sep}...`);
313
+ expect(structure).not.toContain('logs.json');
314
+ });
315
+
316
+ it('should not ignore files if respectGeminiIgnore is false', async () => {
317
+ await fsPromises.writeFile(
318
+ nodePath.join(testRootDir, '.geminiignore'),
319
+ 'ignored.txt\nnode_modules/\n.gemini/\n!/.gemini/config.yaml',
320
+ );
321
+ await createTestFile('file1.txt');
322
+ await createTestFile('node_modules', 'some-package', 'index.js');
323
+ await createTestFile('ignored.txt');
324
+ await createTestFile('.gemini', 'config.yaml');
325
+ await createTestFile('.gemini', 'logs.json');
326
+
327
+ const fileService = new FileDiscoveryService(testRootDir);
328
+ const structure = await getFolderStructure(testRootDir, {
329
+ fileService,
330
+ fileFilteringOptions: {
331
+ respectGeminiIgnore: false,
332
+ respectGitIgnore: true, // Explicitly disable gemini ignore only
333
+ },
334
+ });
335
+ expect(structure).toContain('ignored.txt');
336
+ // node_modules is still ignored by default
337
+ expect(structure).toContain(`node_modules${path.sep}...`);
338
+ });
339
+ });
340
+ });
projects/ui/qwen-code/packages/core/src/utils/getFolderStructure.ts ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { Dirent } from 'fs';
9
+ import * as path from 'path';
10
+ import { getErrorMessage, isNodeError } from './errors.js';
11
+ import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
12
+ import { FileFilteringOptions } from '../config/config.js';
13
+ import { DEFAULT_FILE_FILTERING_OPTIONS } from '../config/config.js';
14
+
15
+ const MAX_ITEMS = 20;
16
+ const TRUNCATION_INDICATOR = '...';
17
+ const DEFAULT_IGNORED_FOLDERS = new Set(['node_modules', '.git', 'dist']);
18
+
19
+ // --- Interfaces ---
20
+
21
+ /** Options for customizing folder structure retrieval. */
22
+ interface FolderStructureOptions {
23
+ /** Maximum number of files and folders combined to display. Defaults to 20. */
24
+ maxItems?: number;
25
+ /** Set of folder names to ignore completely. Case-sensitive. */
26
+ ignoredFolders?: Set<string>;
27
+ /** Optional regex to filter included files by name. */
28
+ fileIncludePattern?: RegExp;
29
+ /** For filtering files. */
30
+ fileService?: FileDiscoveryService;
31
+ /** File filtering ignore options. */
32
+ fileFilteringOptions?: FileFilteringOptions;
33
+ }
34
+ // Define a type for the merged options where fileIncludePattern remains optional
35
+ type MergedFolderStructureOptions = Required<
36
+ Omit<FolderStructureOptions, 'fileIncludePattern' | 'fileService'>
37
+ > & {
38
+ fileIncludePattern?: RegExp;
39
+ fileService?: FileDiscoveryService;
40
+ fileFilteringOptions?: FileFilteringOptions;
41
+ };
42
+
43
+ /** Represents the full, unfiltered information about a folder and its contents. */
44
+ interface FullFolderInfo {
45
+ name: string;
46
+ path: string;
47
+ files: string[];
48
+ subFolders: FullFolderInfo[];
49
+ totalChildren: number; // Number of files and subfolders included from this folder during BFS scan
50
+ totalFiles: number; // Number of files included from this folder during BFS scan
51
+ isIgnored?: boolean; // Flag to easily identify ignored folders later
52
+ hasMoreFiles?: boolean; // Indicates if files were truncated for this specific folder
53
+ hasMoreSubfolders?: boolean; // Indicates if subfolders were truncated for this specific folder
54
+ }
55
+
56
+ // --- Interfaces ---
57
+
58
+ // --- Helper Functions ---
59
+
60
+ async function readFullStructure(
61
+ rootPath: string,
62
+ options: MergedFolderStructureOptions,
63
+ ): Promise<FullFolderInfo | null> {
64
+ const rootName = path.basename(rootPath);
65
+ const rootNode: FullFolderInfo = {
66
+ name: rootName,
67
+ path: rootPath,
68
+ files: [],
69
+ subFolders: [],
70
+ totalChildren: 0,
71
+ totalFiles: 0,
72
+ };
73
+
74
+ const queue: Array<{ folderInfo: FullFolderInfo; currentPath: string }> = [
75
+ { folderInfo: rootNode, currentPath: rootPath },
76
+ ];
77
+ let currentItemCount = 0;
78
+ // Count the root node itself as one item if we are not just listing its content
79
+
80
+ const processedPaths = new Set<string>(); // To avoid processing same path if symlinks create loops
81
+
82
+ while (queue.length > 0) {
83
+ const { folderInfo, currentPath } = queue.shift()!;
84
+
85
+ if (processedPaths.has(currentPath)) {
86
+ continue;
87
+ }
88
+ processedPaths.add(currentPath);
89
+
90
+ if (currentItemCount >= options.maxItems) {
91
+ // If the root itself caused us to exceed, we can't really show anything.
92
+ // Otherwise, this folder won't be processed further.
93
+ // The parent that queued this would have set its own hasMoreSubfolders flag.
94
+ continue;
95
+ }
96
+
97
+ let entries: Dirent[];
98
+ try {
99
+ const rawEntries = await fs.readdir(currentPath, { withFileTypes: true });
100
+ // Sort entries alphabetically by name for consistent processing order
101
+ entries = rawEntries.sort((a, b) => a.name.localeCompare(b.name));
102
+ } catch (error: unknown) {
103
+ if (
104
+ isNodeError(error) &&
105
+ (error.code === 'EACCES' || error.code === 'ENOENT')
106
+ ) {
107
+ console.warn(
108
+ `Warning: Could not read directory ${currentPath}: ${error.message}`,
109
+ );
110
+ if (currentPath === rootPath && error.code === 'ENOENT') {
111
+ return null; // Root directory itself not found
112
+ }
113
+ // For other EACCES/ENOENT on subdirectories, just skip them.
114
+ continue;
115
+ }
116
+ throw error;
117
+ }
118
+
119
+ const filesInCurrentDir: string[] = [];
120
+ const subFoldersInCurrentDir: FullFolderInfo[] = [];
121
+
122
+ // Process files first in the current directory
123
+ for (const entry of entries) {
124
+ if (entry.isFile()) {
125
+ if (currentItemCount >= options.maxItems) {
126
+ folderInfo.hasMoreFiles = true;
127
+ break;
128
+ }
129
+ const fileName = entry.name;
130
+ const filePath = path.join(currentPath, fileName);
131
+ if (options.fileService) {
132
+ const shouldIgnore =
133
+ (options.fileFilteringOptions.respectGitIgnore &&
134
+ options.fileService.shouldGitIgnoreFile(filePath)) ||
135
+ (options.fileFilteringOptions.respectGeminiIgnore &&
136
+ options.fileService.shouldGeminiIgnoreFile(filePath));
137
+ if (shouldIgnore) {
138
+ continue;
139
+ }
140
+ }
141
+ if (
142
+ !options.fileIncludePattern ||
143
+ options.fileIncludePattern.test(fileName)
144
+ ) {
145
+ filesInCurrentDir.push(fileName);
146
+ currentItemCount++;
147
+ folderInfo.totalFiles++;
148
+ folderInfo.totalChildren++;
149
+ }
150
+ }
151
+ }
152
+ folderInfo.files = filesInCurrentDir;
153
+
154
+ // Then process directories and queue them
155
+ for (const entry of entries) {
156
+ if (entry.isDirectory()) {
157
+ // Check if adding this directory ITSELF would meet or exceed maxItems
158
+ // (currentItemCount refers to items *already* added before this one)
159
+ if (currentItemCount >= options.maxItems) {
160
+ folderInfo.hasMoreSubfolders = true;
161
+ break; // Already at limit, cannot add this folder or any more
162
+ }
163
+ // If adding THIS folder makes us hit the limit exactly, and it might have children,
164
+ // it's better to show '...' for the parent, unless this is the very last item slot.
165
+ // This logic is tricky. Let's try a simpler: if we can't add this item, mark and break.
166
+
167
+ const subFolderName = entry.name;
168
+ const subFolderPath = path.join(currentPath, subFolderName);
169
+
170
+ let isIgnored = false;
171
+ if (options.fileService) {
172
+ isIgnored =
173
+ (options.fileFilteringOptions.respectGitIgnore &&
174
+ options.fileService.shouldGitIgnoreFile(subFolderPath)) ||
175
+ (options.fileFilteringOptions.respectGeminiIgnore &&
176
+ options.fileService.shouldGeminiIgnoreFile(subFolderPath));
177
+ }
178
+
179
+ if (options.ignoredFolders.has(subFolderName) || isIgnored) {
180
+ const ignoredSubFolder: FullFolderInfo = {
181
+ name: subFolderName,
182
+ path: subFolderPath,
183
+ files: [],
184
+ subFolders: [],
185
+ totalChildren: 0,
186
+ totalFiles: 0,
187
+ isIgnored: true,
188
+ };
189
+ subFoldersInCurrentDir.push(ignoredSubFolder);
190
+ currentItemCount++; // Count the ignored folder itself
191
+ folderInfo.totalChildren++; // Also counts towards parent's children
192
+ continue;
193
+ }
194
+
195
+ const subFolderNode: FullFolderInfo = {
196
+ name: subFolderName,
197
+ path: subFolderPath,
198
+ files: [],
199
+ subFolders: [],
200
+ totalChildren: 0,
201
+ totalFiles: 0,
202
+ };
203
+ subFoldersInCurrentDir.push(subFolderNode);
204
+ currentItemCount++;
205
+ folderInfo.totalChildren++; // Counts towards parent's children
206
+
207
+ // Add to queue for processing its children later
208
+ queue.push({ folderInfo: subFolderNode, currentPath: subFolderPath });
209
+ }
210
+ }
211
+ folderInfo.subFolders = subFoldersInCurrentDir;
212
+ }
213
+
214
+ return rootNode;
215
+ }
216
+
217
+ /**
218
+ * Reads the directory structure using BFS, respecting maxItems.
219
+ * @param node The current node in the reduced structure.
220
+ * @param indent The current indentation string.
221
+ * @param isLast Sibling indicator.
222
+ * @param builder Array to build the string lines.
223
+ */
224
+ function formatStructure(
225
+ node: FullFolderInfo,
226
+ currentIndent: string,
227
+ isLastChildOfParent: boolean,
228
+ isProcessingRootNode: boolean,
229
+ builder: string[],
230
+ ): void {
231
+ const connector = isLastChildOfParent ? '└───' : '├───';
232
+
233
+ // The root node of the structure (the one passed initially to getFolderStructure)
234
+ // is not printed with a connector line itself, only its name as a header.
235
+ // Its children are printed relative to that conceptual root.
236
+ // Ignored root nodes ARE printed with a connector.
237
+ if (!isProcessingRootNode || node.isIgnored) {
238
+ builder.push(
239
+ `${currentIndent}${connector}${node.name}${path.sep}${node.isIgnored ? TRUNCATION_INDICATOR : ''}`,
240
+ );
241
+ }
242
+
243
+ // Determine the indent for the children of *this* node.
244
+ // If *this* node was the root of the whole structure, its children start with no indent before their connectors.
245
+ // Otherwise, children's indent extends from the current node's indent.
246
+ const indentForChildren = isProcessingRootNode
247
+ ? ''
248
+ : currentIndent + (isLastChildOfParent ? ' ' : '│ ');
249
+
250
+ // Render files of the current node
251
+ const fileCount = node.files.length;
252
+ for (let i = 0; i < fileCount; i++) {
253
+ const isLastFileAmongSiblings =
254
+ i === fileCount - 1 &&
255
+ node.subFolders.length === 0 &&
256
+ !node.hasMoreSubfolders;
257
+ const fileConnector = isLastFileAmongSiblings ? '└───' : '├───';
258
+ builder.push(`${indentForChildren}${fileConnector}${node.files[i]}`);
259
+ }
260
+ if (node.hasMoreFiles) {
261
+ const isLastIndicatorAmongSiblings =
262
+ node.subFolders.length === 0 && !node.hasMoreSubfolders;
263
+ const fileConnector = isLastIndicatorAmongSiblings ? '└───' : '├───';
264
+ builder.push(`${indentForChildren}${fileConnector}${TRUNCATION_INDICATOR}`);
265
+ }
266
+
267
+ // Render subfolders of the current node
268
+ const subFolderCount = node.subFolders.length;
269
+ for (let i = 0; i < subFolderCount; i++) {
270
+ const isLastSubfolderAmongSiblings =
271
+ i === subFolderCount - 1 && !node.hasMoreSubfolders;
272
+ // Children are never the root node being processed initially.
273
+ formatStructure(
274
+ node.subFolders[i],
275
+ indentForChildren,
276
+ isLastSubfolderAmongSiblings,
277
+ false,
278
+ builder,
279
+ );
280
+ }
281
+ if (node.hasMoreSubfolders) {
282
+ builder.push(`${indentForChildren}└───${TRUNCATION_INDICATOR}`);
283
+ }
284
+ }
285
+
286
+ // --- Main Exported Function ---
287
+
288
+ /**
289
+ * Generates a string representation of a directory's structure,
290
+ * limiting the number of items displayed. Ignored folders are shown
291
+ * followed by '...' instead of their contents.
292
+ *
293
+ * @param directory The absolute or relative path to the directory.
294
+ * @param options Optional configuration settings.
295
+ * @returns A promise resolving to the formatted folder structure string.
296
+ */
297
+ export async function getFolderStructure(
298
+ directory: string,
299
+ options?: FolderStructureOptions,
300
+ ): Promise<string> {
301
+ const resolvedPath = path.resolve(directory);
302
+ const mergedOptions: MergedFolderStructureOptions = {
303
+ maxItems: options?.maxItems ?? MAX_ITEMS,
304
+ ignoredFolders: options?.ignoredFolders ?? DEFAULT_IGNORED_FOLDERS,
305
+ fileIncludePattern: options?.fileIncludePattern,
306
+ fileService: options?.fileService,
307
+ fileFilteringOptions:
308
+ options?.fileFilteringOptions ?? DEFAULT_FILE_FILTERING_OPTIONS,
309
+ };
310
+
311
+ try {
312
+ // 1. Read the structure using BFS, respecting maxItems
313
+ const structureRoot = await readFullStructure(resolvedPath, mergedOptions);
314
+
315
+ if (!structureRoot) {
316
+ return `Error: Could not read directory "${resolvedPath}". Check path and permissions.`;
317
+ }
318
+
319
+ // 2. Format the structure into a string
320
+ const structureLines: string[] = [];
321
+ // Pass true for isRoot for the initial call
322
+ formatStructure(structureRoot, '', true, true, structureLines);
323
+
324
+ // 3. Build the final output string
325
+ function isTruncated(node: FullFolderInfo): boolean {
326
+ if (node.hasMoreFiles || node.hasMoreSubfolders || node.isIgnored) {
327
+ return true;
328
+ }
329
+ for (const sub of node.subFolders) {
330
+ if (isTruncated(sub)) {
331
+ return true;
332
+ }
333
+ }
334
+ return false;
335
+ }
336
+
337
+ let summary = `Showing up to ${mergedOptions.maxItems} items (files + folders).`;
338
+
339
+ if (isTruncated(structureRoot)) {
340
+ summary += ` Folders or files indicated with ${TRUNCATION_INDICATOR} contain more items not shown, were ignored, or the display limit (${mergedOptions.maxItems} items) was reached.`;
341
+ }
342
+
343
+ return `${summary}\n\n${resolvedPath}${path.sep}\n${structureLines.join('\n')}`;
344
+ } catch (error: unknown) {
345
+ console.error(`Error getting folder structure for ${resolvedPath}:`, error);
346
+ return `Error processing directory "${resolvedPath}": ${getErrorMessage(error)}`;
347
+ }
348
+ }
projects/ui/qwen-code/packages/core/src/utils/getPty.ts ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ export type PtyImplementation = {
8
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9
+ module: any;
10
+ name: 'lydell-node-pty' | 'node-pty';
11
+ } | null;
12
+
13
+ export interface PtyProcess {
14
+ readonly pid: number;
15
+ onData(callback: (data: string) => void): void;
16
+ onExit(callback: (e: { exitCode: number; signal?: number }) => void): void;
17
+ kill(signal?: string): void;
18
+ }
19
+
20
+ export const getPty = async (): Promise<PtyImplementation> => {
21
+ try {
22
+ const lydell = '@lydell/node-pty';
23
+ const module = await import(lydell);
24
+ return { module, name: 'lydell-node-pty' };
25
+ } catch (_e) {
26
+ try {
27
+ const nodePty = 'node-pty';
28
+ const module = await import(nodePty);
29
+ return { module, name: 'node-pty' };
30
+ } catch (_e2) {
31
+ return null;
32
+ }
33
+ }
34
+ };
projects/ui/qwen-code/packages/core/src/utils/gitIgnoreParser.test.ts ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import { GitIgnoreParser } from './gitIgnoreParser.js';
9
+ import * as fs from 'fs/promises';
10
+ import * as path from 'path';
11
+ import * as os from 'os';
12
+
13
+ describe('GitIgnoreParser', () => {
14
+ let parser: GitIgnoreParser;
15
+ let projectRoot: string;
16
+
17
+ async function createTestFile(filePath: string, content = '') {
18
+ const fullPath = path.join(projectRoot, filePath);
19
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
20
+ await fs.writeFile(fullPath, content);
21
+ }
22
+
23
+ async function setupGitRepo() {
24
+ await fs.mkdir(path.join(projectRoot, '.git'), { recursive: true });
25
+ }
26
+
27
+ beforeEach(async () => {
28
+ projectRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'gitignore-test-'));
29
+ parser = new GitIgnoreParser(projectRoot);
30
+ });
31
+
32
+ afterEach(async () => {
33
+ await fs.rm(projectRoot, { recursive: true, force: true });
34
+ });
35
+
36
+ describe('initialization', () => {
37
+ it('should initialize without errors when no .gitignore exists', async () => {
38
+ await setupGitRepo();
39
+ expect(() => parser.loadGitRepoPatterns()).not.toThrow();
40
+ });
41
+
42
+ it('should load .gitignore patterns when file exists', async () => {
43
+ await setupGitRepo();
44
+ const gitignoreContent = `
45
+ # Comment
46
+ node_modules/
47
+ *.log
48
+ /dist
49
+ .env
50
+ `;
51
+ await createTestFile('.gitignore', gitignoreContent);
52
+
53
+ parser.loadGitRepoPatterns();
54
+
55
+ expect(parser.getPatterns()).toEqual([
56
+ '.git',
57
+ 'node_modules/',
58
+ '*.log',
59
+ '/dist',
60
+ '.env',
61
+ ]);
62
+ expect(parser.isIgnored(path.join('node_modules', 'some-lib'))).toBe(
63
+ true,
64
+ );
65
+ expect(parser.isIgnored(path.join('src', 'app.log'))).toBe(true);
66
+ expect(parser.isIgnored(path.join('dist', 'index.js'))).toBe(true);
67
+ expect(parser.isIgnored('.env')).toBe(true);
68
+ });
69
+
70
+ it('should handle git exclude file', async () => {
71
+ await setupGitRepo();
72
+ await createTestFile(
73
+ path.join('.git', 'info', 'exclude'),
74
+ 'temp/\n*.tmp',
75
+ );
76
+
77
+ parser.loadGitRepoPatterns();
78
+ expect(parser.getPatterns()).toEqual(['.git', 'temp/', '*.tmp']);
79
+ expect(parser.isIgnored(path.join('temp', 'file.txt'))).toBe(true);
80
+ expect(parser.isIgnored(path.join('src', 'file.tmp'))).toBe(true);
81
+ });
82
+
83
+ it('should handle custom patterns file name', async () => {
84
+ // No .git directory for this test
85
+ await createTestFile('.geminiignore', 'temp/\n*.tmp');
86
+
87
+ parser.loadPatterns('.geminiignore');
88
+ expect(parser.getPatterns()).toEqual(['temp/', '*.tmp']);
89
+ expect(parser.isIgnored(path.join('temp', 'file.txt'))).toBe(true);
90
+ expect(parser.isIgnored(path.join('src', 'file.tmp'))).toBe(true);
91
+ });
92
+
93
+ it('should initialize without errors when no .geminiignore exists', () => {
94
+ expect(() => parser.loadPatterns('.geminiignore')).not.toThrow();
95
+ });
96
+ });
97
+
98
+ describe('isIgnored', () => {
99
+ beforeEach(async () => {
100
+ await setupGitRepo();
101
+ const gitignoreContent = `
102
+ node_modules/
103
+ *.log
104
+ /dist
105
+ /.env
106
+ src/*.tmp
107
+ !src/important.tmp
108
+ `;
109
+ await createTestFile('.gitignore', gitignoreContent);
110
+ parser.loadGitRepoPatterns();
111
+ });
112
+
113
+ it('should always ignore .git directory', () => {
114
+ expect(parser.isIgnored('.git')).toBe(true);
115
+ expect(parser.isIgnored(path.join('.git', 'config'))).toBe(true);
116
+ expect(parser.isIgnored(path.join(projectRoot, '.git', 'HEAD'))).toBe(
117
+ true,
118
+ );
119
+ });
120
+
121
+ it('should ignore files matching patterns', () => {
122
+ expect(
123
+ parser.isIgnored(path.join('node_modules', 'package', 'index.js')),
124
+ ).toBe(true);
125
+ expect(parser.isIgnored('app.log')).toBe(true);
126
+ expect(parser.isIgnored(path.join('logs', 'app.log'))).toBe(true);
127
+ expect(parser.isIgnored(path.join('dist', 'bundle.js'))).toBe(true);
128
+ expect(parser.isIgnored('.env')).toBe(true);
129
+ expect(parser.isIgnored(path.join('config', '.env'))).toBe(false); // .env is anchored to root
130
+ });
131
+
132
+ it('should ignore files with path-specific patterns', () => {
133
+ expect(parser.isIgnored(path.join('src', 'temp.tmp'))).toBe(true);
134
+ expect(parser.isIgnored(path.join('other', 'temp.tmp'))).toBe(false);
135
+ });
136
+
137
+ it('should handle negation patterns', () => {
138
+ expect(parser.isIgnored(path.join('src', 'important.tmp'))).toBe(false);
139
+ });
140
+
141
+ it('should not ignore files that do not match patterns', () => {
142
+ expect(parser.isIgnored(path.join('src', 'index.ts'))).toBe(false);
143
+ expect(parser.isIgnored('README.md')).toBe(false);
144
+ });
145
+
146
+ it('should handle absolute paths correctly', () => {
147
+ const absolutePath = path.join(projectRoot, 'node_modules', 'lib');
148
+ expect(parser.isIgnored(absolutePath)).toBe(true);
149
+ });
150
+
151
+ it('should handle paths outside project root by not ignoring them', () => {
152
+ const outsidePath = path.resolve(projectRoot, '..', 'other', 'file.txt');
153
+ expect(parser.isIgnored(outsidePath)).toBe(false);
154
+ });
155
+
156
+ it('should handle relative paths correctly', () => {
157
+ expect(parser.isIgnored(path.join('node_modules', 'some-package'))).toBe(
158
+ true,
159
+ );
160
+ expect(
161
+ parser.isIgnored(path.join('..', 'some', 'other', 'file.txt')),
162
+ ).toBe(false);
163
+ });
164
+
165
+ it('should normalize path separators on Windows', () => {
166
+ expect(parser.isIgnored(path.join('node_modules', 'package'))).toBe(true);
167
+ expect(parser.isIgnored(path.join('src', 'temp.tmp'))).toBe(true);
168
+ });
169
+
170
+ it('should handle root path "/" without throwing error', () => {
171
+ expect(() => parser.isIgnored('/')).not.toThrow();
172
+ expect(parser.isIgnored('/')).toBe(false);
173
+ });
174
+
175
+ it('should handle absolute-like paths without throwing error', () => {
176
+ expect(() => parser.isIgnored('/some/path')).not.toThrow();
177
+ expect(parser.isIgnored('/some/path')).toBe(false);
178
+ });
179
+
180
+ it('should handle paths that start with forward slash', () => {
181
+ expect(() => parser.isIgnored('/node_modules')).not.toThrow();
182
+ expect(parser.isIgnored('/node_modules')).toBe(false);
183
+ });
184
+ });
185
+
186
+ describe('getIgnoredPatterns', () => {
187
+ it('should return the raw patterns added', async () => {
188
+ await setupGitRepo();
189
+ const gitignoreContent = '*.log\n!important.log';
190
+ await createTestFile('.gitignore', gitignoreContent);
191
+
192
+ parser.loadGitRepoPatterns();
193
+ expect(parser.getPatterns()).toEqual(['.git', '*.log', '!important.log']);
194
+ });
195
+ });
196
+ });