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

Add files using upload-large-folder tool

Browse files
projects/ui/qwen-code/packages/core/src/utils/gitIgnoreParser.ts ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'fs';
8
+ import * as path from 'path';
9
+ import ignore, { type Ignore } from 'ignore';
10
+ import { isGitRepository } from './gitUtils.js';
11
+
12
+ export interface GitIgnoreFilter {
13
+ isIgnored(filePath: string): boolean;
14
+ getPatterns(): string[];
15
+ }
16
+
17
+ export class GitIgnoreParser implements GitIgnoreFilter {
18
+ private projectRoot: string;
19
+ private ig: Ignore = ignore();
20
+ private patterns: string[] = [];
21
+
22
+ constructor(projectRoot: string) {
23
+ this.projectRoot = path.resolve(projectRoot);
24
+ }
25
+
26
+ loadGitRepoPatterns(): void {
27
+ if (!isGitRepository(this.projectRoot)) return;
28
+
29
+ // Always ignore .git directory regardless of .gitignore content
30
+ this.addPatterns(['.git']);
31
+
32
+ const patternFiles = ['.gitignore', path.join('.git', 'info', 'exclude')];
33
+ for (const pf of patternFiles) {
34
+ this.loadPatterns(pf);
35
+ }
36
+ }
37
+
38
+ loadPatterns(patternsFileName: string): void {
39
+ const patternsFilePath = path.join(this.projectRoot, patternsFileName);
40
+ let content: string;
41
+ try {
42
+ content = fs.readFileSync(patternsFilePath, 'utf-8');
43
+ } catch (_error) {
44
+ // ignore file not found
45
+ return;
46
+ }
47
+ const patterns = (content ?? '')
48
+ .split('\n')
49
+ .map((p) => p.trim())
50
+ .filter((p) => p !== '' && !p.startsWith('#'));
51
+ this.addPatterns(patterns);
52
+ }
53
+
54
+ private addPatterns(patterns: string[]) {
55
+ this.ig.add(patterns);
56
+ this.patterns.push(...patterns);
57
+ }
58
+
59
+ isIgnored(filePath: string): boolean {
60
+ const resolved = path.resolve(this.projectRoot, filePath);
61
+ const relativePath = path.relative(this.projectRoot, resolved);
62
+
63
+ if (relativePath === '' || relativePath.startsWith('..')) {
64
+ return false;
65
+ }
66
+
67
+ // Even in windows, Ignore expects forward slashes.
68
+ const normalizedPath = relativePath.replace(/\\/g, '/');
69
+ return this.ig.ignores(normalizedPath);
70
+ }
71
+
72
+ getPatterns(): string[] {
73
+ return this.patterns;
74
+ }
75
+ }
projects/ui/qwen-code/packages/core/src/utils/gitUtils.ts ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'fs';
8
+ import * as path from 'path';
9
+
10
+ /**
11
+ * Checks if a directory is within a git repository
12
+ * @param directory The directory to check
13
+ * @returns true if the directory is in a git repository, false otherwise
14
+ */
15
+ export function isGitRepository(directory: string): boolean {
16
+ try {
17
+ let currentDir = path.resolve(directory);
18
+
19
+ while (true) {
20
+ const gitDir = path.join(currentDir, '.git');
21
+
22
+ // Check if .git exists (either as directory or file for worktrees)
23
+ if (fs.existsSync(gitDir)) {
24
+ return true;
25
+ }
26
+
27
+ const parentDir = path.dirname(currentDir);
28
+
29
+ // If we've reached the root directory, stop searching
30
+ if (parentDir === currentDir) {
31
+ break;
32
+ }
33
+
34
+ currentDir = parentDir;
35
+ }
36
+
37
+ return false;
38
+ } catch (_error) {
39
+ // If any filesystem error occurs, assume not a git repo
40
+ return false;
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Finds the root directory of a git repository
46
+ * @param directory Starting directory to search from
47
+ * @returns The git repository root path, or null if not in a git repository
48
+ */
49
+ export function findGitRoot(directory: string): string | null {
50
+ try {
51
+ let currentDir = path.resolve(directory);
52
+
53
+ while (true) {
54
+ const gitDir = path.join(currentDir, '.git');
55
+
56
+ if (fs.existsSync(gitDir)) {
57
+ return currentDir;
58
+ }
59
+
60
+ const parentDir = path.dirname(currentDir);
61
+
62
+ if (parentDir === currentDir) {
63
+ break;
64
+ }
65
+
66
+ currentDir = parentDir;
67
+ }
68
+
69
+ return null;
70
+ } catch (_error) {
71
+ return null;
72
+ }
73
+ }
projects/ui/qwen-code/packages/core/src/utils/memoryDiscovery.test.ts ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import * as fsPromises from 'fs/promises';
9
+ import * as os from 'os';
10
+ import * as path from 'path';
11
+ import { loadServerHierarchicalMemory } from './memoryDiscovery.js';
12
+ import {
13
+ GEMINI_CONFIG_DIR,
14
+ setGeminiMdFilename,
15
+ DEFAULT_CONTEXT_FILENAME,
16
+ } from '../tools/memoryTool.js';
17
+ import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
18
+
19
+ vi.mock('os', async (importOriginal) => {
20
+ const actualOs = await importOriginal<typeof os>();
21
+ return {
22
+ ...actualOs,
23
+ homedir: vi.fn(),
24
+ };
25
+ });
26
+
27
+ describe('loadServerHierarchicalMemory', () => {
28
+ let testRootDir: string;
29
+ let cwd: string;
30
+ let projectRoot: string;
31
+ let homedir: string;
32
+
33
+ async function createEmptyDir(fullPath: string) {
34
+ await fsPromises.mkdir(fullPath, { recursive: true });
35
+ return fullPath;
36
+ }
37
+
38
+ async function createTestFile(fullPath: string, fileContents: string) {
39
+ await fsPromises.mkdir(path.dirname(fullPath), { recursive: true });
40
+ await fsPromises.writeFile(fullPath, fileContents);
41
+ return path.resolve(testRootDir, fullPath);
42
+ }
43
+
44
+ beforeEach(async () => {
45
+ testRootDir = await fsPromises.mkdtemp(
46
+ path.join(os.tmpdir(), 'folder-structure-test-'),
47
+ );
48
+
49
+ vi.resetAllMocks();
50
+ // Set environment variables to indicate test environment
51
+ vi.stubEnv('NODE_ENV', 'test');
52
+ vi.stubEnv('VITEST', 'true');
53
+
54
+ projectRoot = await createEmptyDir(path.join(testRootDir, 'project'));
55
+ cwd = await createEmptyDir(path.join(projectRoot, 'src'));
56
+ homedir = await createEmptyDir(path.join(testRootDir, 'userhome'));
57
+ vi.mocked(os.homedir).mockReturnValue(homedir);
58
+ });
59
+
60
+ afterEach(async () => {
61
+ vi.unstubAllEnvs();
62
+ // Some tests set this to a different value.
63
+ setGeminiMdFilename(DEFAULT_CONTEXT_FILENAME);
64
+ // Clean up the temporary directory to prevent resource leaks.
65
+ await fsPromises.rm(testRootDir, { recursive: true, force: true });
66
+ });
67
+
68
+ it('should return empty memory and count if no context files are found', async () => {
69
+ const result = await loadServerHierarchicalMemory(
70
+ cwd,
71
+ [],
72
+ false,
73
+ new FileDiscoveryService(projectRoot),
74
+ );
75
+
76
+ expect(result).toEqual({
77
+ memoryContent: '',
78
+ fileCount: 0,
79
+ });
80
+ });
81
+
82
+ it('should load only the global context file if present and others are not (default filename)', async () => {
83
+ const defaultContextFile = await createTestFile(
84
+ path.join(homedir, GEMINI_CONFIG_DIR, DEFAULT_CONTEXT_FILENAME),
85
+ 'default context content',
86
+ );
87
+
88
+ const result = await loadServerHierarchicalMemory(
89
+ cwd,
90
+ [],
91
+ false,
92
+ new FileDiscoveryService(projectRoot),
93
+ );
94
+
95
+ expect(result).toEqual({
96
+ memoryContent: `--- Context from: ${path.relative(cwd, defaultContextFile)} ---\ndefault context content\n--- End of Context from: ${path.relative(cwd, defaultContextFile)} ---`,
97
+ fileCount: 1,
98
+ });
99
+ });
100
+
101
+ it('should load only the global custom context file if present and filename is changed', async () => {
102
+ const customFilename = 'CUSTOM_AGENTS.md';
103
+ setGeminiMdFilename(customFilename);
104
+
105
+ const customContextFile = await createTestFile(
106
+ path.join(homedir, GEMINI_CONFIG_DIR, customFilename),
107
+ 'custom context content',
108
+ );
109
+
110
+ const result = await loadServerHierarchicalMemory(
111
+ cwd,
112
+ [],
113
+ false,
114
+ new FileDiscoveryService(projectRoot),
115
+ );
116
+
117
+ expect(result).toEqual({
118
+ memoryContent: `--- Context from: ${path.relative(cwd, customContextFile)} ---\ncustom context content\n--- End of Context from: ${path.relative(cwd, customContextFile)} ---`,
119
+ fileCount: 1,
120
+ });
121
+ });
122
+
123
+ it('should load context files by upward traversal with custom filename', async () => {
124
+ const customFilename = 'PROJECT_CONTEXT.md';
125
+ setGeminiMdFilename(customFilename);
126
+
127
+ const projectContextFile = await createTestFile(
128
+ path.join(projectRoot, customFilename),
129
+ 'project context content',
130
+ );
131
+ const cwdContextFile = await createTestFile(
132
+ path.join(cwd, customFilename),
133
+ 'cwd context content',
134
+ );
135
+
136
+ const result = await loadServerHierarchicalMemory(
137
+ cwd,
138
+ [],
139
+ false,
140
+ new FileDiscoveryService(projectRoot),
141
+ );
142
+
143
+ expect(result).toEqual({
144
+ memoryContent: `--- Context from: ${path.relative(cwd, projectContextFile)} ---\nproject context content\n--- End of Context from: ${path.relative(cwd, projectContextFile)} ---\n\n--- Context from: ${path.relative(cwd, cwdContextFile)} ---\ncwd context content\n--- End of Context from: ${path.relative(cwd, cwdContextFile)} ---`,
145
+ fileCount: 2,
146
+ });
147
+ });
148
+
149
+ it('should load context files by downward traversal with custom filename', async () => {
150
+ const customFilename = 'LOCAL_CONTEXT.md';
151
+ setGeminiMdFilename(customFilename);
152
+
153
+ await createTestFile(
154
+ path.join(cwd, 'subdir', customFilename),
155
+ 'Subdir custom memory',
156
+ );
157
+ await createTestFile(path.join(cwd, customFilename), 'CWD custom memory');
158
+
159
+ const result = await loadServerHierarchicalMemory(
160
+ cwd,
161
+ [],
162
+ false,
163
+ new FileDiscoveryService(projectRoot),
164
+ );
165
+
166
+ expect(result).toEqual({
167
+ memoryContent: `--- Context from: ${customFilename} ---\nCWD custom memory\n--- End of Context from: ${customFilename} ---\n\n--- Context from: ${path.join('subdir', customFilename)} ---\nSubdir custom memory\n--- End of Context from: ${path.join('subdir', customFilename)} ---`,
168
+ fileCount: 2,
169
+ });
170
+ });
171
+
172
+ it('should load ORIGINAL_GEMINI_MD_FILENAME files by upward traversal from CWD to project root', async () => {
173
+ const projectRootGeminiFile = await createTestFile(
174
+ path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
175
+ 'Project root memory',
176
+ );
177
+ const srcGeminiFile = await createTestFile(
178
+ path.join(cwd, DEFAULT_CONTEXT_FILENAME),
179
+ 'Src directory memory',
180
+ );
181
+
182
+ const result = await loadServerHierarchicalMemory(
183
+ cwd,
184
+ [],
185
+ false,
186
+ new FileDiscoveryService(projectRoot),
187
+ );
188
+
189
+ expect(result).toEqual({
190
+ memoryContent: `--- Context from: ${path.relative(cwd, projectRootGeminiFile)} ---\nProject root memory\n--- End of Context from: ${path.relative(cwd, projectRootGeminiFile)} ---\n\n--- Context from: ${path.relative(cwd, srcGeminiFile)} ---\nSrc directory memory\n--- End of Context from: ${path.relative(cwd, srcGeminiFile)} ---`,
191
+ fileCount: 2,
192
+ });
193
+ });
194
+
195
+ it('should load ORIGINAL_GEMINI_MD_FILENAME files by downward traversal from CWD', async () => {
196
+ await createTestFile(
197
+ path.join(cwd, 'subdir', DEFAULT_CONTEXT_FILENAME),
198
+ 'Subdir memory',
199
+ );
200
+ await createTestFile(
201
+ path.join(cwd, DEFAULT_CONTEXT_FILENAME),
202
+ 'CWD memory',
203
+ );
204
+
205
+ const result = await loadServerHierarchicalMemory(
206
+ cwd,
207
+ [],
208
+ false,
209
+ new FileDiscoveryService(projectRoot),
210
+ );
211
+
212
+ expect(result).toEqual({
213
+ memoryContent: `--- Context from: ${DEFAULT_CONTEXT_FILENAME} ---\nCWD memory\n--- End of Context from: ${DEFAULT_CONTEXT_FILENAME} ---\n\n--- Context from: ${path.join('subdir', DEFAULT_CONTEXT_FILENAME)} ---\nSubdir memory\n--- End of Context from: ${path.join('subdir', DEFAULT_CONTEXT_FILENAME)} ---`,
214
+ fileCount: 2,
215
+ });
216
+ });
217
+
218
+ it('should load and correctly order global, upward, and downward ORIGINAL_GEMINI_MD_FILENAME files', async () => {
219
+ const defaultContextFile = await createTestFile(
220
+ path.join(homedir, GEMINI_CONFIG_DIR, DEFAULT_CONTEXT_FILENAME),
221
+ 'default context content',
222
+ );
223
+ const rootGeminiFile = await createTestFile(
224
+ path.join(testRootDir, DEFAULT_CONTEXT_FILENAME),
225
+ 'Project parent memory',
226
+ );
227
+ const projectRootGeminiFile = await createTestFile(
228
+ path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
229
+ 'Project root memory',
230
+ );
231
+ const cwdGeminiFile = await createTestFile(
232
+ path.join(cwd, DEFAULT_CONTEXT_FILENAME),
233
+ 'CWD memory',
234
+ );
235
+ const subDirGeminiFile = await createTestFile(
236
+ path.join(cwd, 'sub', DEFAULT_CONTEXT_FILENAME),
237
+ 'Subdir memory',
238
+ );
239
+
240
+ const result = await loadServerHierarchicalMemory(
241
+ cwd,
242
+ [],
243
+ false,
244
+ new FileDiscoveryService(projectRoot),
245
+ );
246
+
247
+ expect(result).toEqual({
248
+ memoryContent: `--- Context from: ${path.relative(cwd, defaultContextFile)} ---\ndefault context content\n--- End of Context from: ${path.relative(cwd, defaultContextFile)} ---\n\n--- Context from: ${path.relative(cwd, rootGeminiFile)} ---\nProject parent memory\n--- End of Context from: ${path.relative(cwd, rootGeminiFile)} ---\n\n--- Context from: ${path.relative(cwd, projectRootGeminiFile)} ---\nProject root memory\n--- End of Context from: ${path.relative(cwd, projectRootGeminiFile)} ---\n\n--- Context from: ${path.relative(cwd, cwdGeminiFile)} ---\nCWD memory\n--- End of Context from: ${path.relative(cwd, cwdGeminiFile)} ---\n\n--- Context from: ${path.relative(cwd, subDirGeminiFile)} ---\nSubdir memory\n--- End of Context from: ${path.relative(cwd, subDirGeminiFile)} ---`,
249
+ fileCount: 5,
250
+ });
251
+ });
252
+
253
+ it('should ignore specified directories during downward scan', async () => {
254
+ await createEmptyDir(path.join(projectRoot, '.git'));
255
+ await createTestFile(path.join(projectRoot, '.gitignore'), 'node_modules');
256
+
257
+ await createTestFile(
258
+ path.join(cwd, 'node_modules', DEFAULT_CONTEXT_FILENAME),
259
+ 'Ignored memory',
260
+ );
261
+ const regularSubDirGeminiFile = await createTestFile(
262
+ path.join(cwd, 'my_code', DEFAULT_CONTEXT_FILENAME),
263
+ 'My code memory',
264
+ );
265
+
266
+ const result = await loadServerHierarchicalMemory(
267
+ cwd,
268
+ [],
269
+ false,
270
+ new FileDiscoveryService(projectRoot),
271
+ [],
272
+ 'tree',
273
+ {
274
+ respectGitIgnore: true,
275
+ respectGeminiIgnore: true,
276
+ },
277
+ 200, // maxDirs parameter
278
+ );
279
+
280
+ expect(result).toEqual({
281
+ memoryContent: `--- Context from: ${path.relative(cwd, regularSubDirGeminiFile)} ---\nMy code memory\n--- End of Context from: ${path.relative(cwd, regularSubDirGeminiFile)} ---`,
282
+ fileCount: 1,
283
+ });
284
+ });
285
+
286
+ it('should respect the maxDirs parameter during downward scan', async () => {
287
+ const consoleDebugSpy = vi
288
+ .spyOn(console, 'debug')
289
+ .mockImplementation(() => {});
290
+
291
+ for (let i = 0; i < 100; i++) {
292
+ await createEmptyDir(path.join(cwd, `deep_dir_${i}`));
293
+ }
294
+
295
+ // Pass the custom limit directly to the function
296
+ await loadServerHierarchicalMemory(
297
+ cwd,
298
+ [],
299
+ true,
300
+ new FileDiscoveryService(projectRoot),
301
+ [],
302
+ 'tree', // importFormat
303
+ {
304
+ respectGitIgnore: true,
305
+ respectGeminiIgnore: true,
306
+ },
307
+ 50, // maxDirs
308
+ );
309
+
310
+ expect(consoleDebugSpy).toHaveBeenCalledWith(
311
+ expect.stringContaining('[DEBUG] [BfsFileSearch]'),
312
+ expect.stringContaining('Scanning [50/50]:'),
313
+ );
314
+
315
+ vi.mocked(console.debug).mockRestore();
316
+
317
+ const result = await loadServerHierarchicalMemory(
318
+ cwd,
319
+ [],
320
+ false,
321
+ new FileDiscoveryService(projectRoot),
322
+ );
323
+
324
+ expect(result).toEqual({
325
+ memoryContent: '',
326
+ fileCount: 0,
327
+ });
328
+ });
329
+
330
+ it('should load extension context file paths', async () => {
331
+ const extensionFilePath = await createTestFile(
332
+ path.join(testRootDir, 'extensions/ext1/QWEN.md'),
333
+ 'Extension memory content',
334
+ );
335
+
336
+ const result = await loadServerHierarchicalMemory(
337
+ cwd,
338
+ [],
339
+ false,
340
+ new FileDiscoveryService(projectRoot),
341
+ [extensionFilePath],
342
+ );
343
+
344
+ expect(result).toEqual({
345
+ memoryContent: `--- Context from: ${path.relative(cwd, extensionFilePath)} ---\nExtension memory content\n--- End of Context from: ${path.relative(cwd, extensionFilePath)} ---`,
346
+ fileCount: 1,
347
+ });
348
+ });
349
+
350
+ it('should load memory from included directories', async () => {
351
+ const includedDir = await createEmptyDir(
352
+ path.join(testRootDir, 'included'),
353
+ );
354
+ const includedFile = await createTestFile(
355
+ path.join(includedDir, DEFAULT_CONTEXT_FILENAME),
356
+ 'included directory memory',
357
+ );
358
+
359
+ const result = await loadServerHierarchicalMemory(
360
+ cwd,
361
+ [includedDir],
362
+ false,
363
+ new FileDiscoveryService(projectRoot),
364
+ );
365
+
366
+ expect(result).toEqual({
367
+ memoryContent: `--- Context from: ${path.relative(cwd, includedFile)} ---\nincluded directory memory\n--- End of Context from: ${path.relative(cwd, includedFile)} ---`,
368
+ fileCount: 1,
369
+ });
370
+ });
371
+ });
projects/ui/qwen-code/packages/core/src/utils/memoryDiscovery.ts ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 * as fsSync from 'fs';
9
+ import * as path from 'path';
10
+ import { homedir } from 'os';
11
+ import { bfsFileSearch } from './bfsFileSearch.js';
12
+ import {
13
+ GEMINI_CONFIG_DIR,
14
+ getAllGeminiMdFilenames,
15
+ } from '../tools/memoryTool.js';
16
+ import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
17
+ import { processImports } from './memoryImportProcessor.js';
18
+ import {
19
+ DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
20
+ FileFilteringOptions,
21
+ } from '../config/config.js';
22
+
23
+ // Simple console logger, similar to the one previously in CLI's config.ts
24
+ // TODO: Integrate with a more robust server-side logger if available/appropriate.
25
+ const logger = {
26
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
27
+ debug: (...args: any[]) =>
28
+ console.debug('[DEBUG] [MemoryDiscovery]', ...args),
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ warn: (...args: any[]) => console.warn('[WARN] [MemoryDiscovery]', ...args),
31
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
32
+ error: (...args: any[]) =>
33
+ console.error('[ERROR] [MemoryDiscovery]', ...args),
34
+ };
35
+
36
+ interface GeminiFileContent {
37
+ filePath: string;
38
+ content: string | null;
39
+ }
40
+
41
+ async function findProjectRoot(startDir: string): Promise<string | null> {
42
+ let currentDir = path.resolve(startDir);
43
+ while (true) {
44
+ const gitPath = path.join(currentDir, '.git');
45
+ try {
46
+ const stats = await fs.lstat(gitPath);
47
+ if (stats.isDirectory()) {
48
+ return currentDir;
49
+ }
50
+ } catch (error: unknown) {
51
+ // Don't log ENOENT errors as they're expected when .git doesn't exist
52
+ // Also don't log errors in test environments, which often have mocked fs
53
+ const isENOENT =
54
+ typeof error === 'object' &&
55
+ error !== null &&
56
+ 'code' in error &&
57
+ (error as { code: string }).code === 'ENOENT';
58
+
59
+ // Only log unexpected errors in non-test environments
60
+ // process.env['NODE_ENV'] === 'test' or VITEST are common test indicators
61
+ const isTestEnv =
62
+ process.env['NODE_ENV'] === 'test' || process.env['VITEST'];
63
+
64
+ if (!isENOENT && !isTestEnv) {
65
+ if (typeof error === 'object' && error !== null && 'code' in error) {
66
+ const fsError = error as { code: string; message: string };
67
+ logger.warn(
68
+ `Error checking for .git directory at ${gitPath}: ${fsError.message}`,
69
+ );
70
+ } else {
71
+ logger.warn(
72
+ `Non-standard error checking for .git directory at ${gitPath}: ${String(error)}`,
73
+ );
74
+ }
75
+ }
76
+ }
77
+ const parentDir = path.dirname(currentDir);
78
+ if (parentDir === currentDir) {
79
+ return null;
80
+ }
81
+ currentDir = parentDir;
82
+ }
83
+ }
84
+
85
+ async function getGeminiMdFilePathsInternal(
86
+ currentWorkingDirectory: string,
87
+ includeDirectoriesToReadGemini: readonly string[],
88
+ userHomePath: string,
89
+ debugMode: boolean,
90
+ fileService: FileDiscoveryService,
91
+ extensionContextFilePaths: string[] = [],
92
+ fileFilteringOptions: FileFilteringOptions,
93
+ maxDirs: number,
94
+ ): Promise<string[]> {
95
+ const dirs = new Set<string>([
96
+ ...includeDirectoriesToReadGemini,
97
+ currentWorkingDirectory,
98
+ ]);
99
+ const paths = [];
100
+ for (const dir of dirs) {
101
+ const pathsByDir = await getGeminiMdFilePathsInternalForEachDir(
102
+ dir,
103
+ userHomePath,
104
+ debugMode,
105
+ fileService,
106
+ extensionContextFilePaths,
107
+ fileFilteringOptions,
108
+ maxDirs,
109
+ );
110
+ paths.push(...pathsByDir);
111
+ }
112
+ return Array.from(new Set<string>(paths));
113
+ }
114
+
115
+ async function getGeminiMdFilePathsInternalForEachDir(
116
+ dir: string,
117
+ userHomePath: string,
118
+ debugMode: boolean,
119
+ fileService: FileDiscoveryService,
120
+ extensionContextFilePaths: string[] = [],
121
+ fileFilteringOptions: FileFilteringOptions,
122
+ maxDirs: number,
123
+ ): Promise<string[]> {
124
+ const allPaths = new Set<string>();
125
+ const geminiMdFilenames = getAllGeminiMdFilenames();
126
+
127
+ for (const geminiMdFilename of geminiMdFilenames) {
128
+ const resolvedHome = path.resolve(userHomePath);
129
+ const globalMemoryPath = path.join(
130
+ resolvedHome,
131
+ GEMINI_CONFIG_DIR,
132
+ geminiMdFilename,
133
+ );
134
+
135
+ // This part that finds the global file always runs.
136
+ try {
137
+ await fs.access(globalMemoryPath, fsSync.constants.R_OK);
138
+ allPaths.add(globalMemoryPath);
139
+ if (debugMode)
140
+ logger.debug(
141
+ `Found readable global ${geminiMdFilename}: ${globalMemoryPath}`,
142
+ );
143
+ } catch {
144
+ // It's okay if it's not found.
145
+ }
146
+
147
+ // Handle the case where we're in the home directory (dir is empty string or home path)
148
+ const resolvedDir = dir ? path.resolve(dir) : resolvedHome;
149
+ const isHomeDirectory = resolvedDir === resolvedHome;
150
+
151
+ if (isHomeDirectory) {
152
+ // For home directory, only check for QWEN.md directly in the home directory
153
+ const homeContextPath = path.join(resolvedHome, geminiMdFilename);
154
+ try {
155
+ await fs.access(homeContextPath, fsSync.constants.R_OK);
156
+ if (homeContextPath !== globalMemoryPath) {
157
+ allPaths.add(homeContextPath);
158
+ if (debugMode)
159
+ logger.debug(
160
+ `Found readable home ${geminiMdFilename}: ${homeContextPath}`,
161
+ );
162
+ }
163
+ } catch {
164
+ // Not found, which is okay
165
+ }
166
+ } else if (dir) {
167
+ // FIX: Only perform the workspace search (upward and downward scans)
168
+ // if a valid currentWorkingDirectory is provided and it's not the home directory.
169
+ const resolvedCwd = path.resolve(dir);
170
+ if (debugMode)
171
+ logger.debug(
172
+ `Searching for ${geminiMdFilename} starting from CWD: ${resolvedCwd}`,
173
+ );
174
+
175
+ const projectRoot = await findProjectRoot(resolvedCwd);
176
+ if (debugMode)
177
+ logger.debug(`Determined project root: ${projectRoot ?? 'None'}`);
178
+
179
+ const upwardPaths: string[] = [];
180
+ let currentDir = resolvedCwd;
181
+ const ultimateStopDir = projectRoot
182
+ ? path.dirname(projectRoot)
183
+ : path.dirname(resolvedHome);
184
+
185
+ while (currentDir && currentDir !== path.dirname(currentDir)) {
186
+ if (currentDir === path.join(resolvedHome, GEMINI_CONFIG_DIR)) {
187
+ break;
188
+ }
189
+
190
+ const potentialPath = path.join(currentDir, geminiMdFilename);
191
+ try {
192
+ await fs.access(potentialPath, fsSync.constants.R_OK);
193
+ if (potentialPath !== globalMemoryPath) {
194
+ upwardPaths.unshift(potentialPath);
195
+ }
196
+ } catch {
197
+ // Not found, continue.
198
+ }
199
+
200
+ if (currentDir === ultimateStopDir) {
201
+ break;
202
+ }
203
+
204
+ currentDir = path.dirname(currentDir);
205
+ }
206
+ upwardPaths.forEach((p) => allPaths.add(p));
207
+
208
+ const mergedOptions = {
209
+ ...DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
210
+ ...fileFilteringOptions,
211
+ };
212
+
213
+ const downwardPaths = await bfsFileSearch(resolvedCwd, {
214
+ fileName: geminiMdFilename,
215
+ maxDirs,
216
+ debug: debugMode,
217
+ fileService,
218
+ fileFilteringOptions: mergedOptions,
219
+ });
220
+ downwardPaths.sort();
221
+ for (const dPath of downwardPaths) {
222
+ allPaths.add(dPath);
223
+ }
224
+ }
225
+ }
226
+
227
+ // Add extension context file paths.
228
+ for (const extensionPath of extensionContextFilePaths) {
229
+ allPaths.add(extensionPath);
230
+ }
231
+
232
+ const finalPaths = Array.from(allPaths);
233
+
234
+ if (debugMode)
235
+ logger.debug(
236
+ `Final ordered ${getAllGeminiMdFilenames()} paths to read: ${JSON.stringify(
237
+ finalPaths,
238
+ )}`,
239
+ );
240
+ return finalPaths;
241
+ }
242
+
243
+ async function readGeminiMdFiles(
244
+ filePaths: string[],
245
+ debugMode: boolean,
246
+ importFormat: 'flat' | 'tree' = 'tree',
247
+ ): Promise<GeminiFileContent[]> {
248
+ const results: GeminiFileContent[] = [];
249
+ for (const filePath of filePaths) {
250
+ try {
251
+ const content = await fs.readFile(filePath, 'utf-8');
252
+
253
+ // Process imports in the content
254
+ const processedResult = await processImports(
255
+ content,
256
+ path.dirname(filePath),
257
+ debugMode,
258
+ undefined,
259
+ undefined,
260
+ importFormat,
261
+ );
262
+
263
+ results.push({ filePath, content: processedResult.content });
264
+ if (debugMode)
265
+ logger.debug(
266
+ `Successfully read and processed imports: ${filePath} (Length: ${processedResult.content.length})`,
267
+ );
268
+ } catch (error: unknown) {
269
+ const isTestEnv =
270
+ process.env['NODE_ENV'] === 'test' || process.env['VITEST'];
271
+ if (!isTestEnv) {
272
+ const message = error instanceof Error ? error.message : String(error);
273
+ logger.warn(
274
+ `Warning: Could not read ${getAllGeminiMdFilenames()} file at ${filePath}. Error: ${message}`,
275
+ );
276
+ }
277
+ results.push({ filePath, content: null }); // Still include it with null content
278
+ if (debugMode) logger.debug(`Failed to read: ${filePath}`);
279
+ }
280
+ }
281
+ return results;
282
+ }
283
+
284
+ function concatenateInstructions(
285
+ instructionContents: GeminiFileContent[],
286
+ // CWD is needed to resolve relative paths for display markers
287
+ currentWorkingDirectoryForDisplay: string,
288
+ ): string {
289
+ return instructionContents
290
+ .filter((item) => typeof item.content === 'string')
291
+ .map((item) => {
292
+ const trimmedContent = (item.content as string).trim();
293
+ if (trimmedContent.length === 0) {
294
+ return null;
295
+ }
296
+ const displayPath = path.isAbsolute(item.filePath)
297
+ ? path.relative(currentWorkingDirectoryForDisplay, item.filePath)
298
+ : item.filePath;
299
+ return `--- Context from: ${displayPath} ---\n${trimmedContent}\n--- End of Context from: ${displayPath} ---`;
300
+ })
301
+ .filter((block): block is string => block !== null)
302
+ .join('\n\n');
303
+ }
304
+
305
+ /**
306
+ * Loads hierarchical QWEN.md files and concatenates their content.
307
+ * This function is intended for use by the server.
308
+ */
309
+ export async function loadServerHierarchicalMemory(
310
+ currentWorkingDirectory: string,
311
+ includeDirectoriesToReadGemini: readonly string[],
312
+ debugMode: boolean,
313
+ fileService: FileDiscoveryService,
314
+ extensionContextFilePaths: string[] = [],
315
+ importFormat: 'flat' | 'tree' = 'tree',
316
+ fileFilteringOptions?: FileFilteringOptions,
317
+ maxDirs: number = 200,
318
+ ): Promise<{ memoryContent: string; fileCount: number }> {
319
+ if (debugMode)
320
+ logger.debug(
321
+ `Loading server hierarchical memory for CWD: ${currentWorkingDirectory} (importFormat: ${importFormat})`,
322
+ );
323
+
324
+ // For the server, homedir() refers to the server process's home.
325
+ // This is consistent with how MemoryTool already finds the global path.
326
+ const userHomePath = homedir();
327
+ const filePaths = await getGeminiMdFilePathsInternal(
328
+ currentWorkingDirectory,
329
+ includeDirectoriesToReadGemini,
330
+ userHomePath,
331
+ debugMode,
332
+ fileService,
333
+ extensionContextFilePaths,
334
+ fileFilteringOptions || DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,
335
+ maxDirs,
336
+ );
337
+ if (filePaths.length === 0) {
338
+ if (debugMode) logger.debug('No QWEN.md files found in hierarchy.');
339
+ return { memoryContent: '', fileCount: 0 };
340
+ }
341
+ const contentsWithPaths = await readGeminiMdFiles(
342
+ filePaths,
343
+ debugMode,
344
+ importFormat,
345
+ );
346
+ // Pass CWD for relative path display in concatenated content
347
+ const combinedInstructions = concatenateInstructions(
348
+ contentsWithPaths,
349
+ currentWorkingDirectory,
350
+ );
351
+ if (debugMode)
352
+ logger.debug(
353
+ `Combined instructions length: ${combinedInstructions.length}`,
354
+ );
355
+ if (debugMode && combinedInstructions.length > 0)
356
+ logger.debug(
357
+ `Combined instructions (snippet): ${combinedInstructions.substring(0, 500)}...`,
358
+ );
359
+ return {
360
+ memoryContent: combinedInstructions,
361
+ fileCount: contentsWithPaths.length,
362
+ };
363
+ }
projects/ui/qwen-code/packages/core/src/utils/memoryImportProcessor.test.ts ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 * as fs from 'fs/promises';
9
+ import * as path from 'path';
10
+ import { marked } from 'marked';
11
+ import { processImports, validateImportPath } from './memoryImportProcessor.js';
12
+
13
+ // Helper function to create platform-agnostic test paths
14
+ function testPath(...segments: string[]): string {
15
+ // Start with the first segment as is (might be an absolute path on Windows)
16
+ let result = segments[0];
17
+
18
+ // Join remaining segments with the platform-specific separator
19
+ for (let i = 1; i < segments.length; i++) {
20
+ if (segments[i].startsWith('/') || segments[i].startsWith('\\')) {
21
+ // If segment starts with a separator, remove the trailing separator from the result
22
+ result = path.normalize(result.replace(/[\\/]+$/, '') + segments[i]);
23
+ } else {
24
+ // Otherwise join with the platform separator
25
+ result = path.join(result, segments[i]);
26
+ }
27
+ }
28
+
29
+ return path.normalize(result);
30
+ }
31
+
32
+ vi.mock('fs/promises');
33
+ const mockedFs = vi.mocked(fs);
34
+
35
+ // Mock console methods to capture warnings
36
+ const originalConsoleWarn = console.warn;
37
+ const originalConsoleError = console.error;
38
+ const originalConsoleDebug = console.debug;
39
+
40
+ // Helper functions using marked for parsing and validation
41
+ const parseMarkdown = (content: string) => marked.lexer(content);
42
+
43
+ const findMarkdownComments = (content: string): string[] => {
44
+ const tokens = parseMarkdown(content);
45
+ const comments: string[] = [];
46
+
47
+ function walkTokens(tokenList: unknown[]) {
48
+ for (const token of tokenList) {
49
+ const t = token as { type: string; raw: string; tokens?: unknown[] };
50
+ if (t.type === 'html' && t.raw.includes('<!--')) {
51
+ comments.push(t.raw.trim());
52
+ }
53
+ if (t.tokens) {
54
+ walkTokens(t.tokens);
55
+ }
56
+ }
57
+ }
58
+
59
+ walkTokens(tokens);
60
+ return comments;
61
+ };
62
+
63
+ const findCodeBlocks = (
64
+ content: string,
65
+ ): Array<{ type: string; content: string }> => {
66
+ const tokens = parseMarkdown(content);
67
+ const codeBlocks: Array<{ type: string; content: string }> = [];
68
+
69
+ function walkTokens(tokenList: unknown[]) {
70
+ for (const token of tokenList) {
71
+ const t = token as { type: string; text: string; tokens?: unknown[] };
72
+ if (t.type === 'code') {
73
+ codeBlocks.push({
74
+ type: 'code_block',
75
+ content: t.text,
76
+ });
77
+ } else if (t.type === 'codespan') {
78
+ codeBlocks.push({
79
+ type: 'inline_code',
80
+ content: t.text,
81
+ });
82
+ }
83
+ if (t.tokens) {
84
+ walkTokens(t.tokens);
85
+ }
86
+ }
87
+ }
88
+
89
+ walkTokens(tokens);
90
+ return codeBlocks;
91
+ };
92
+
93
+ describe('memoryImportProcessor', () => {
94
+ beforeEach(() => {
95
+ vi.clearAllMocks();
96
+ // Mock console methods
97
+ console.warn = vi.fn();
98
+ console.error = vi.fn();
99
+ console.debug = vi.fn();
100
+ });
101
+
102
+ afterEach(() => {
103
+ // Restore console methods
104
+ console.warn = originalConsoleWarn;
105
+ console.error = originalConsoleError;
106
+ console.debug = originalConsoleDebug;
107
+ });
108
+
109
+ describe('processImports', () => {
110
+ it('should process basic md file imports', async () => {
111
+ const content = 'Some content @./test.md more content';
112
+ const basePath = testPath('test', 'path');
113
+ const importedContent = '# Imported Content\nThis is imported.';
114
+
115
+ mockedFs.access.mockResolvedValue(undefined);
116
+ mockedFs.readFile.mockResolvedValue(importedContent);
117
+
118
+ const result = await processImports(content, basePath, true);
119
+
120
+ // Use marked to find HTML comments (import markers)
121
+ const comments = findMarkdownComments(result.content);
122
+ expect(comments.some((c) => c.includes('Imported from: ./test.md'))).toBe(
123
+ true,
124
+ );
125
+ expect(
126
+ comments.some((c) => c.includes('End of import from: ./test.md')),
127
+ ).toBe(true);
128
+
129
+ // Verify the imported content is present
130
+ expect(result.content).toContain(importedContent);
131
+
132
+ // Verify the markdown structure is valid
133
+ const tokens = parseMarkdown(result.content);
134
+ expect(tokens).toBeDefined();
135
+ expect(tokens.length).toBeGreaterThan(0);
136
+
137
+ expect(mockedFs.readFile).toHaveBeenCalledWith(
138
+ path.resolve(basePath, './test.md'),
139
+ 'utf-8',
140
+ );
141
+ });
142
+
143
+ it('should import non-md files just like md files', async () => {
144
+ const content = 'Some content @./instructions.txt more content';
145
+ const basePath = testPath('test', 'path');
146
+ const importedContent =
147
+ '# Instructions\nThis is a text file with markdown.';
148
+
149
+ mockedFs.access.mockResolvedValue(undefined);
150
+ mockedFs.readFile.mockResolvedValue(importedContent);
151
+
152
+ const result = await processImports(content, basePath, true);
153
+
154
+ // Use marked to find import comments
155
+ const comments = findMarkdownComments(result.content);
156
+ expect(
157
+ comments.some((c) => c.includes('Imported from: ./instructions.txt')),
158
+ ).toBe(true);
159
+ expect(
160
+ comments.some((c) =>
161
+ c.includes('End of import from: ./instructions.txt'),
162
+ ),
163
+ ).toBe(true);
164
+
165
+ // Use marked to parse and validate the imported content structure
166
+ const tokens = parseMarkdown(result.content);
167
+
168
+ // Find headers in the parsed content
169
+ const headers = tokens.filter((token) => token.type === 'heading');
170
+ expect(
171
+ headers.some((h) => (h as { text: string }).text === 'Instructions'),
172
+ ).toBe(true);
173
+
174
+ // Verify the imported content is present
175
+ expect(result.content).toContain(importedContent);
176
+ expect(console.warn).not.toHaveBeenCalled();
177
+ expect(mockedFs.readFile).toHaveBeenCalledWith(
178
+ path.resolve(basePath, './instructions.txt'),
179
+ 'utf-8',
180
+ );
181
+ });
182
+
183
+ it('should handle circular imports', async () => {
184
+ const content = 'Content @./circular.md more content';
185
+ const basePath = testPath('test', 'path');
186
+ const circularContent = 'Circular @./main.md content';
187
+
188
+ mockedFs.access.mockResolvedValue(undefined);
189
+ mockedFs.readFile.mockResolvedValue(circularContent);
190
+
191
+ // Set up the import state to simulate we're already processing main.md
192
+ const importState = {
193
+ processedFiles: new Set<string>(),
194
+ maxDepth: 10,
195
+ currentDepth: 0,
196
+ currentFile: testPath('test', 'path', 'main.md'), // Simulate we're processing main.md
197
+ };
198
+
199
+ const result = await processImports(content, basePath, true, importState);
200
+
201
+ // The circular import should be detected when processing the nested import
202
+ expect(result.content).toContain(
203
+ '<!-- File already processed: ./main.md -->',
204
+ );
205
+ });
206
+
207
+ it('should handle file not found errors', async () => {
208
+ const content = 'Content @./nonexistent.md more content';
209
+ const basePath = testPath('test', 'path');
210
+
211
+ mockedFs.access.mockRejectedValue(new Error('File not found'));
212
+
213
+ const result = await processImports(content, basePath, true);
214
+
215
+ expect(result.content).toContain(
216
+ '<!-- Import failed: ./nonexistent.md - File not found -->',
217
+ );
218
+ expect(console.error).toHaveBeenCalledWith(
219
+ '[ERROR] [ImportProcessor]',
220
+ 'Failed to import ./nonexistent.md: File not found',
221
+ );
222
+ });
223
+
224
+ it('should respect max depth limit', async () => {
225
+ const content = 'Content @./deep.md more content';
226
+ const basePath = testPath('test', 'path');
227
+ const deepContent = 'Deep @./deeper.md content';
228
+
229
+ mockedFs.access.mockResolvedValue(undefined);
230
+ mockedFs.readFile.mockResolvedValue(deepContent);
231
+
232
+ const importState = {
233
+ processedFiles: new Set<string>(),
234
+ maxDepth: 1,
235
+ currentDepth: 1,
236
+ };
237
+
238
+ const result = await processImports(content, basePath, true, importState);
239
+
240
+ expect(console.warn).toHaveBeenCalledWith(
241
+ '[WARN] [ImportProcessor]',
242
+ 'Maximum import depth (1) reached. Stopping import processing.',
243
+ );
244
+ expect(result.content).toBe(content);
245
+ });
246
+
247
+ it('should handle nested imports recursively', async () => {
248
+ const content = 'Main @./nested.md content';
249
+ const basePath = testPath('test', 'path');
250
+ const nestedContent = 'Nested @./inner.md content';
251
+ const innerContent = 'Inner content';
252
+
253
+ mockedFs.access.mockResolvedValue(undefined);
254
+ mockedFs.readFile
255
+ .mockResolvedValueOnce(nestedContent)
256
+ .mockResolvedValueOnce(innerContent);
257
+
258
+ const result = await processImports(content, basePath, true);
259
+
260
+ expect(result.content).toContain('<!-- Imported from: ./nested.md -->');
261
+ expect(result.content).toContain('<!-- Imported from: ./inner.md -->');
262
+ expect(result.content).toContain(innerContent);
263
+ });
264
+
265
+ it('should handle absolute paths in imports', async () => {
266
+ const content = 'Content @/absolute/path/file.md more content';
267
+ const basePath = testPath('test', 'path');
268
+ const importedContent = 'Absolute path content';
269
+
270
+ mockedFs.access.mockResolvedValue(undefined);
271
+ mockedFs.readFile.mockResolvedValue(importedContent);
272
+
273
+ const result = await processImports(content, basePath, true);
274
+
275
+ expect(result.content).toContain(
276
+ '<!-- Import failed: /absolute/path/file.md - Path traversal attempt -->',
277
+ );
278
+ });
279
+
280
+ it('should handle multiple imports in same content', async () => {
281
+ const content = 'Start @./first.md middle @./second.md end';
282
+ const basePath = testPath('test', 'path');
283
+ const firstContent = 'First content';
284
+ const secondContent = 'Second content';
285
+
286
+ mockedFs.access.mockResolvedValue(undefined);
287
+ mockedFs.readFile
288
+ .mockResolvedValueOnce(firstContent)
289
+ .mockResolvedValueOnce(secondContent);
290
+
291
+ const result = await processImports(content, basePath, true);
292
+
293
+ expect(result.content).toContain('<!-- Imported from: ./first.md -->');
294
+ expect(result.content).toContain('<!-- Imported from: ./second.md -->');
295
+ expect(result.content).toContain(firstContent);
296
+ expect(result.content).toContain(secondContent);
297
+ });
298
+
299
+ it('should ignore imports inside code blocks', async () => {
300
+ const content = [
301
+ 'Normal content @./should-import.md',
302
+ '```',
303
+ 'code block with @./should-not-import.md',
304
+ '```',
305
+ 'More content @./should-import2.md',
306
+ ].join('\n');
307
+ const projectRoot = testPath('test', 'project');
308
+ const basePath = testPath(projectRoot, 'src');
309
+ const importedContent1 = 'Imported 1';
310
+ const importedContent2 = 'Imported 2';
311
+ // Only the imports outside code blocks should be processed
312
+ mockedFs.access.mockResolvedValue(undefined);
313
+ mockedFs.readFile
314
+ .mockResolvedValueOnce(importedContent1)
315
+ .mockResolvedValueOnce(importedContent2);
316
+ const result = await processImports(
317
+ content,
318
+ basePath,
319
+ true,
320
+ undefined,
321
+ projectRoot,
322
+ );
323
+
324
+ // Use marked to verify imported content is present
325
+ expect(result.content).toContain(importedContent1);
326
+ expect(result.content).toContain(importedContent2);
327
+
328
+ // Use marked to find code blocks and verify the import wasn't processed
329
+ const codeBlocks = findCodeBlocks(result.content);
330
+ const hasUnprocessedImport = codeBlocks.some((block) =>
331
+ block.content.includes('@./should-not-import.md'),
332
+ );
333
+ expect(hasUnprocessedImport).toBe(true);
334
+
335
+ // Verify no import comment was created for the code block import
336
+ const comments = findMarkdownComments(result.content);
337
+ expect(comments.some((c) => c.includes('should-not-import.md'))).toBe(
338
+ false,
339
+ );
340
+ });
341
+
342
+ it('should ignore imports inside inline code', async () => {
343
+ const content = [
344
+ 'Normal content @./should-import.md',
345
+ '`code with import @./should-not-import.md`',
346
+ 'More content @./should-import2.md',
347
+ ].join('\n');
348
+ const projectRoot = testPath('test', 'project');
349
+ const basePath = testPath(projectRoot, 'src');
350
+ const importedContent1 = 'Imported 1';
351
+ const importedContent2 = 'Imported 2';
352
+ mockedFs.access.mockResolvedValue(undefined);
353
+ mockedFs.readFile
354
+ .mockResolvedValueOnce(importedContent1)
355
+ .mockResolvedValueOnce(importedContent2);
356
+ const result = await processImports(
357
+ content,
358
+ basePath,
359
+ true,
360
+ undefined,
361
+ projectRoot,
362
+ );
363
+
364
+ // Verify imported content is present
365
+ expect(result.content).toContain(importedContent1);
366
+ expect(result.content).toContain(importedContent2);
367
+
368
+ // Use marked to find inline code spans
369
+ const codeBlocks = findCodeBlocks(result.content);
370
+ const inlineCodeSpans = codeBlocks.filter(
371
+ (block) => block.type === 'inline_code',
372
+ );
373
+
374
+ // Verify the inline code span still contains the unprocessed import
375
+ expect(
376
+ inlineCodeSpans.some((span) =>
377
+ span.content.includes('@./should-not-import.md'),
378
+ ),
379
+ ).toBe(true);
380
+
381
+ // Verify no import comments were created for inline code imports
382
+ const comments = findMarkdownComments(result.content);
383
+ expect(comments.some((c) => c.includes('should-not-import.md'))).toBe(
384
+ false,
385
+ );
386
+ });
387
+
388
+ it('should handle nested tokens and non-unique content correctly', async () => {
389
+ // This test verifies the robust findCodeRegions implementation
390
+ // that recursively walks the token tree and handles non-unique content
391
+ const content = [
392
+ 'Normal content @./should-import.md',
393
+ 'Paragraph with `inline code @./should-not-import.md` and more text.',
394
+ 'Another paragraph with the same `inline code @./should-not-import.md` text.',
395
+ 'More content @./should-import2.md',
396
+ ].join('\n');
397
+ const projectRoot = testPath('test', 'project');
398
+ const basePath = testPath(projectRoot, 'src');
399
+ const importedContent1 = 'Imported 1';
400
+ const importedContent2 = 'Imported 2';
401
+ mockedFs.access.mockResolvedValue(undefined);
402
+ mockedFs.readFile
403
+ .mockResolvedValueOnce(importedContent1)
404
+ .mockResolvedValueOnce(importedContent2);
405
+ const result = await processImports(
406
+ content,
407
+ basePath,
408
+ true,
409
+ undefined,
410
+ projectRoot,
411
+ );
412
+
413
+ // Should process imports outside code regions
414
+ expect(result.content).toContain(importedContent1);
415
+ expect(result.content).toContain(importedContent2);
416
+
417
+ // Should preserve imports inside inline code (both occurrences)
418
+ expect(result.content).toContain('`inline code @./should-not-import.md`');
419
+
420
+ // Should not have processed the imports inside code regions
421
+ expect(result.content).not.toContain(
422
+ '<!-- Imported from: ./should-not-import.md -->',
423
+ );
424
+ });
425
+
426
+ it('should allow imports from parent and subdirectories within project root', async () => {
427
+ const content =
428
+ 'Parent import: @../parent.md Subdir import: @./components/sub.md';
429
+ const projectRoot = testPath('test', 'project');
430
+ const basePath = testPath(projectRoot, 'src');
431
+ const importedParent = 'Parent file content';
432
+ const importedSub = 'Subdir file content';
433
+ mockedFs.access.mockResolvedValue(undefined);
434
+ mockedFs.readFile
435
+ .mockResolvedValueOnce(importedParent)
436
+ .mockResolvedValueOnce(importedSub);
437
+ const result = await processImports(
438
+ content,
439
+ basePath,
440
+ true,
441
+ undefined,
442
+ projectRoot,
443
+ );
444
+ expect(result.content).toContain(importedParent);
445
+ expect(result.content).toContain(importedSub);
446
+ });
447
+
448
+ it('should reject imports outside project root', async () => {
449
+ const content = 'Outside import: @../../../etc/passwd';
450
+ const projectRoot = testPath('test', 'project');
451
+ const basePath = testPath(projectRoot, 'src');
452
+ const result = await processImports(
453
+ content,
454
+ basePath,
455
+ true,
456
+ undefined,
457
+ projectRoot,
458
+ );
459
+ expect(result.content).toContain(
460
+ '<!-- Import failed: ../../../etc/passwd - Path traversal attempt -->',
461
+ );
462
+ });
463
+
464
+ it('should build import tree structure', async () => {
465
+ const content = 'Main content @./nested.md @./simple.md';
466
+ const projectRoot = testPath('test', 'project');
467
+ const basePath = testPath(projectRoot, 'src');
468
+ const nestedContent = 'Nested @./inner.md content';
469
+ const simpleContent = 'Simple content';
470
+ const innerContent = 'Inner content';
471
+
472
+ mockedFs.access.mockResolvedValue(undefined);
473
+ mockedFs.readFile
474
+ .mockResolvedValueOnce(nestedContent)
475
+ .mockResolvedValueOnce(simpleContent)
476
+ .mockResolvedValueOnce(innerContent);
477
+
478
+ const result = await processImports(content, basePath, true);
479
+
480
+ // Use marked to find and validate import comments
481
+ const comments = findMarkdownComments(result.content);
482
+ const importComments = comments.filter((c) =>
483
+ c.includes('Imported from:'),
484
+ );
485
+
486
+ expect(importComments.some((c) => c.includes('./nested.md'))).toBe(true);
487
+ expect(importComments.some((c) => c.includes('./simple.md'))).toBe(true);
488
+ expect(importComments.some((c) => c.includes('./inner.md'))).toBe(true);
489
+
490
+ // Use marked to validate the markdown structure is well-formed
491
+ const tokens = parseMarkdown(result.content);
492
+ expect(tokens).toBeDefined();
493
+ expect(tokens.length).toBeGreaterThan(0);
494
+
495
+ // Verify the content contains expected text using marked parsing
496
+ const textContent = tokens
497
+ .filter((token) => token.type === 'paragraph')
498
+ .map((token) => token.raw)
499
+ .join(' ');
500
+
501
+ expect(textContent).toContain('Main content');
502
+ expect(textContent).toContain('Nested');
503
+ expect(textContent).toContain('Simple content');
504
+ expect(textContent).toContain('Inner content');
505
+
506
+ // Verify import tree structure
507
+ expect(result.importTree.path).toBe('unknown'); // No currentFile set in test
508
+ expect(result.importTree.imports).toHaveLength(2);
509
+
510
+ // First import: nested.md
511
+ // Check that the paths match using includes to handle potential absolute/relative differences
512
+ const expectedNestedPath = testPath(projectRoot, 'src', 'nested.md');
513
+
514
+ expect(result.importTree.imports![0].path).toContain(expectedNestedPath);
515
+ expect(result.importTree.imports![0].imports).toHaveLength(1);
516
+
517
+ const expectedInnerPath = testPath(projectRoot, 'src', 'inner.md');
518
+ expect(result.importTree.imports![0].imports![0].path).toContain(
519
+ expectedInnerPath,
520
+ );
521
+ expect(result.importTree.imports![0].imports![0].imports).toBeUndefined();
522
+
523
+ // Second import: simple.md
524
+ const expectedSimplePath = testPath(projectRoot, 'src', 'simple.md');
525
+ expect(result.importTree.imports![1].path).toContain(expectedSimplePath);
526
+ expect(result.importTree.imports![1].imports).toBeUndefined();
527
+ });
528
+
529
+ it('should produce flat output in Claude-style with unique files in order', async () => {
530
+ const content = 'Main @./nested.md content @./simple.md';
531
+ const projectRoot = testPath('test', 'project');
532
+ const basePath = testPath(projectRoot, 'src');
533
+ const nestedContent = 'Nested @./inner.md content';
534
+ const simpleContent = 'Simple content';
535
+ const innerContent = 'Inner content';
536
+
537
+ mockedFs.access.mockResolvedValue(undefined);
538
+ mockedFs.readFile
539
+ .mockResolvedValueOnce(nestedContent)
540
+ .mockResolvedValueOnce(simpleContent)
541
+ .mockResolvedValueOnce(innerContent);
542
+
543
+ const result = await processImports(
544
+ content,
545
+ basePath,
546
+ true,
547
+ undefined,
548
+ projectRoot,
549
+ 'flat',
550
+ );
551
+
552
+ // Use marked to parse the output and validate structure
553
+ const tokens = parseMarkdown(result.content);
554
+ expect(tokens).toBeDefined();
555
+
556
+ // Find all file markers using marked parsing
557
+ const fileMarkers: string[] = [];
558
+ const endMarkers: string[] = [];
559
+
560
+ function walkTokens(tokenList: unknown[]) {
561
+ for (const token of tokenList) {
562
+ const t = token as { type: string; raw: string; tokens?: unknown[] };
563
+ if (t.type === 'paragraph' && t.raw.includes('--- File:')) {
564
+ const match = t.raw.match(/--- File: (.+?) ---/);
565
+ if (match) {
566
+ // Normalize the path before adding to fileMarkers
567
+ fileMarkers.push(path.normalize(match[1]));
568
+ }
569
+ }
570
+ if (t.type === 'paragraph' && t.raw.includes('--- End of File:')) {
571
+ const match = t.raw.match(/--- End of File: (.+?) ---/);
572
+ if (match) {
573
+ // Normalize the path before adding to endMarkers
574
+ endMarkers.push(path.normalize(match[1]));
575
+ }
576
+ }
577
+ if (t.tokens) {
578
+ walkTokens(t.tokens);
579
+ }
580
+ }
581
+ }
582
+
583
+ walkTokens(tokens);
584
+
585
+ // Verify all expected files are present
586
+ const expectedFiles = ['nested.md', 'simple.md', 'inner.md'];
587
+
588
+ // Check that each expected file is present in the content
589
+ expectedFiles.forEach((file) => {
590
+ expect(result.content).toContain(file);
591
+ });
592
+
593
+ // Verify content is present
594
+ expect(result.content).toContain(
595
+ 'Main @./nested.md content @./simple.md',
596
+ );
597
+ expect(result.content).toContain('Nested @./inner.md content');
598
+ expect(result.content).toContain('Simple content');
599
+ expect(result.content).toContain('Inner content');
600
+
601
+ // Verify end markers exist
602
+ expect(endMarkers.length).toBeGreaterThan(0);
603
+ });
604
+
605
+ it('should not duplicate files in flat output if imported multiple times', async () => {
606
+ const content = 'Main @./dup.md again @./dup.md';
607
+ const projectRoot = testPath('test', 'project');
608
+ const basePath = testPath(projectRoot, 'src');
609
+ const dupContent = 'Duplicated content';
610
+
611
+ // Reset mocks
612
+ mockedFs.access.mockReset();
613
+ mockedFs.readFile.mockReset();
614
+
615
+ // Set up mocks
616
+ mockedFs.access.mockResolvedValue(undefined);
617
+ mockedFs.readFile.mockResolvedValue(dupContent);
618
+
619
+ const result = await processImports(
620
+ content,
621
+ basePath,
622
+ true, // followImports
623
+ undefined, // allowedPaths
624
+ projectRoot,
625
+ 'flat', // outputFormat
626
+ );
627
+
628
+ // Verify readFile was called only once for dup.md
629
+ expect(mockedFs.readFile).toHaveBeenCalledTimes(1);
630
+
631
+ // Check that the content contains the file content only once
632
+ const contentStr = result.content;
633
+ const firstIndex = contentStr.indexOf('Duplicated content');
634
+ const lastIndex = contentStr.lastIndexOf('Duplicated content');
635
+ expect(firstIndex).toBeGreaterThan(-1); // Content should exist
636
+ expect(firstIndex).toBe(lastIndex); // Should only appear once
637
+ });
638
+
639
+ it('should handle nested imports in flat output', async () => {
640
+ const content = 'Root @./a.md';
641
+ const projectRoot = testPath('test', 'project');
642
+ const basePath = testPath(projectRoot, 'src');
643
+ const aContent = 'A @./b.md';
644
+ const bContent = 'B content';
645
+
646
+ mockedFs.access.mockResolvedValue(undefined);
647
+ mockedFs.readFile
648
+ .mockResolvedValueOnce(aContent)
649
+ .mockResolvedValueOnce(bContent);
650
+
651
+ const result = await processImports(
652
+ content,
653
+ basePath,
654
+ true,
655
+ undefined,
656
+ projectRoot,
657
+ 'flat',
658
+ );
659
+
660
+ // Verify all files are present by checking for their basenames
661
+ expect(result.content).toContain('a.md');
662
+ expect(result.content).toContain('b.md');
663
+
664
+ // Verify content is in the correct order
665
+ const contentStr = result.content;
666
+ const aIndex = contentStr.indexOf('a.md');
667
+ const bIndex = contentStr.indexOf('b.md');
668
+ const rootIndex = contentStr.indexOf('Root @./a.md');
669
+
670
+ expect(rootIndex).toBeLessThan(aIndex);
671
+ expect(aIndex).toBeLessThan(bIndex);
672
+
673
+ // Verify content is present
674
+ expect(result.content).toContain('Root @./a.md');
675
+ expect(result.content).toContain('A @./b.md');
676
+ expect(result.content).toContain('B content');
677
+ });
678
+
679
+ it('should build import tree structure', async () => {
680
+ const content = 'Main content @./nested.md @./simple.md';
681
+ const projectRoot = testPath('test', 'project');
682
+ const basePath = testPath(projectRoot, 'src');
683
+ const nestedContent = 'Nested @./inner.md content';
684
+ const simpleContent = 'Simple content';
685
+ const innerContent = 'Inner content';
686
+
687
+ mockedFs.access.mockResolvedValue(undefined);
688
+ mockedFs.readFile
689
+ .mockResolvedValueOnce(nestedContent)
690
+ .mockResolvedValueOnce(simpleContent)
691
+ .mockResolvedValueOnce(innerContent);
692
+
693
+ const result = await processImports(content, basePath, true);
694
+
695
+ // Use marked to find and validate import comments
696
+ const comments = findMarkdownComments(result.content);
697
+ const importComments = comments.filter((c) =>
698
+ c.includes('Imported from:'),
699
+ );
700
+
701
+ expect(importComments.some((c) => c.includes('./nested.md'))).toBe(true);
702
+ expect(importComments.some((c) => c.includes('./simple.md'))).toBe(true);
703
+ expect(importComments.some((c) => c.includes('./inner.md'))).toBe(true);
704
+
705
+ // Use marked to validate the markdown structure is well-formed
706
+ const tokens = parseMarkdown(result.content);
707
+ expect(tokens).toBeDefined();
708
+ expect(tokens.length).toBeGreaterThan(0);
709
+
710
+ // Verify the content contains expected text using marked parsing
711
+ const textContent = tokens
712
+ .filter((token) => token.type === 'paragraph')
713
+ .map((token) => token.raw)
714
+ .join(' ');
715
+
716
+ expect(textContent).toContain('Main content');
717
+ expect(textContent).toContain('Nested');
718
+ expect(textContent).toContain('Simple content');
719
+ expect(textContent).toContain('Inner content');
720
+
721
+ // Verify import tree structure
722
+ expect(result.importTree.path).toBe('unknown'); // No currentFile set in test
723
+ expect(result.importTree.imports).toHaveLength(2);
724
+
725
+ // First import: nested.md
726
+ const expectedNestedPath = testPath(projectRoot, 'src', 'nested.md');
727
+ const expectedInnerPath = testPath(projectRoot, 'src', 'inner.md');
728
+ const expectedSimplePath = testPath(projectRoot, 'src', 'simple.md');
729
+
730
+ // Check that the paths match using includes to handle potential absolute/relative differences
731
+ expect(result.importTree.imports![0].path).toContain(expectedNestedPath);
732
+ expect(result.importTree.imports![0].imports).toHaveLength(1);
733
+ expect(result.importTree.imports![0].imports![0].path).toContain(
734
+ expectedInnerPath,
735
+ );
736
+ expect(result.importTree.imports![0].imports![0].imports).toBeUndefined();
737
+
738
+ // Second import: simple.md
739
+ expect(result.importTree.imports![1].path).toContain(expectedSimplePath);
740
+ expect(result.importTree.imports![1].imports).toBeUndefined();
741
+ });
742
+
743
+ it('should produce flat output in Claude-style with unique files in order', async () => {
744
+ const content = 'Main @./nested.md content @./simple.md';
745
+ const projectRoot = testPath('test', 'project');
746
+ const basePath = testPath(projectRoot, 'src');
747
+ const nestedContent = 'Nested @./inner.md content';
748
+ const simpleContent = 'Simple content';
749
+ const innerContent = 'Inner content';
750
+
751
+ mockedFs.access.mockResolvedValue(undefined);
752
+ mockedFs.readFile
753
+ .mockResolvedValueOnce(nestedContent)
754
+ .mockResolvedValueOnce(simpleContent)
755
+ .mockResolvedValueOnce(innerContent);
756
+
757
+ const result = await processImports(
758
+ content,
759
+ basePath,
760
+ true,
761
+ undefined,
762
+ projectRoot,
763
+ 'flat',
764
+ );
765
+
766
+ // Verify all expected files are present by checking for their basenames
767
+ expect(result.content).toContain('nested.md');
768
+ expect(result.content).toContain('simple.md');
769
+ expect(result.content).toContain('inner.md');
770
+
771
+ // Verify content is present
772
+ expect(result.content).toContain('Nested @./inner.md content');
773
+ expect(result.content).toContain('Simple content');
774
+ expect(result.content).toContain('Inner content');
775
+ });
776
+
777
+ it('should not duplicate files in flat output if imported multiple times', async () => {
778
+ const content = 'Main @./dup.md again @./dup.md';
779
+ const projectRoot = testPath('test', 'project');
780
+ const basePath = testPath(projectRoot, 'src');
781
+ const dupContent = 'Duplicated content';
782
+
783
+ // Create a normalized path for the duplicate file
784
+ const dupFilePath = path.normalize(path.join(basePath, 'dup.md'));
785
+
786
+ // Mock the file system access
787
+ mockedFs.access.mockImplementation((filePath) => {
788
+ const pathStr = filePath.toString();
789
+ if (path.normalize(pathStr) === dupFilePath) {
790
+ return Promise.resolve();
791
+ }
792
+ return Promise.reject(new Error(`File not found: ${pathStr}`));
793
+ });
794
+
795
+ // Mock the file reading
796
+ mockedFs.readFile.mockImplementation((filePath) => {
797
+ const pathStr = filePath.toString();
798
+ if (path.normalize(pathStr) === dupFilePath) {
799
+ return Promise.resolve(dupContent);
800
+ }
801
+ return Promise.reject(new Error(`File not found: ${pathStr}`));
802
+ });
803
+
804
+ const result = await processImports(
805
+ content,
806
+ basePath,
807
+ true, // debugMode
808
+ undefined, // importState
809
+ projectRoot,
810
+ 'flat',
811
+ );
812
+
813
+ // In flat mode, the output should only contain the main file content with import markers
814
+ // The imported file content should not be included in the flat output
815
+ expect(result.content).toContain('Main @./dup.md again @./dup.md');
816
+
817
+ // The imported file content should not appear in the output
818
+ // This is the current behavior of the implementation
819
+ expect(result.content).not.toContain(dupContent);
820
+
821
+ // The file marker should not appear in the output
822
+ // since the imported file content is not included in flat mode
823
+ const fileMarker = `--- File: ${dupFilePath} ---`;
824
+ expect(result.content).not.toContain(fileMarker);
825
+ expect(result.content).not.toContain('--- End of File: ' + dupFilePath);
826
+
827
+ // The main file path should be in the output
828
+ // Since we didn't pass an importState, it will use the basePath as the file path
829
+ const mainFilePath = path.normalize(path.resolve(basePath));
830
+ expect(result.content).toContain(`--- File: ${mainFilePath} ---`);
831
+ expect(result.content).toContain(`--- End of File: ${mainFilePath}`);
832
+ });
833
+
834
+ it('should handle nested imports in flat output', async () => {
835
+ const content = 'Root @./a.md';
836
+ const projectRoot = testPath('test', 'project');
837
+ const basePath = testPath(projectRoot, 'src');
838
+ const aContent = 'A @./b.md';
839
+ const bContent = 'B content';
840
+
841
+ mockedFs.access.mockResolvedValue(undefined);
842
+ mockedFs.readFile
843
+ .mockResolvedValueOnce(aContent)
844
+ .mockResolvedValueOnce(bContent);
845
+
846
+ const result = await processImports(
847
+ content,
848
+ basePath,
849
+ true,
850
+ undefined,
851
+ projectRoot,
852
+ 'flat',
853
+ );
854
+
855
+ // Verify all files are present by checking for their basenames
856
+ expect(result.content).toContain('a.md');
857
+ expect(result.content).toContain('b.md');
858
+
859
+ // Verify content is in the correct order
860
+ const contentStr = result.content;
861
+ const aIndex = contentStr.indexOf('a.md');
862
+ const bIndex = contentStr.indexOf('b.md');
863
+ const rootIndex = contentStr.indexOf('Root @./a.md');
864
+
865
+ expect(rootIndex).toBeLessThan(aIndex);
866
+ expect(aIndex).toBeLessThan(bIndex);
867
+
868
+ // Verify content is present
869
+ expect(result.content).toContain('Root @./a.md');
870
+ expect(result.content).toContain('A @./b.md');
871
+ expect(result.content).toContain('B content');
872
+ });
873
+ });
874
+
875
+ describe('validateImportPath', () => {
876
+ it('should reject URLs', () => {
877
+ const basePath = testPath('base');
878
+ const allowedPath = testPath('allowed');
879
+ expect(
880
+ validateImportPath('https://example.com/file.md', basePath, [
881
+ allowedPath,
882
+ ]),
883
+ ).toBe(false);
884
+ expect(
885
+ validateImportPath('http://example.com/file.md', basePath, [
886
+ allowedPath,
887
+ ]),
888
+ ).toBe(false);
889
+ expect(
890
+ validateImportPath('file:///path/to/file.md', basePath, [allowedPath]),
891
+ ).toBe(false);
892
+ });
893
+
894
+ it('should allow paths within allowed directories', () => {
895
+ const basePath = path.resolve(testPath('base'));
896
+ const allowedPath = path.resolve(testPath('allowed'));
897
+
898
+ // Test relative paths - resolve them against basePath
899
+ const relativePath = './file.md';
900
+ path.resolve(basePath, relativePath);
901
+ expect(validateImportPath(relativePath, basePath, [basePath])).toBe(true);
902
+
903
+ // Test parent directory access (should be allowed if parent is in allowed paths)
904
+ const parentPath = path.dirname(basePath);
905
+ if (parentPath !== basePath) {
906
+ // Only test if parent is different
907
+ const parentRelativePath = '../file.md';
908
+ path.resolve(basePath, parentRelativePath);
909
+ expect(
910
+ validateImportPath(parentRelativePath, basePath, [parentPath]),
911
+ ).toBe(true);
912
+
913
+ path.resolve(basePath, 'sub');
914
+ const resultSub = validateImportPath('sub', basePath, [basePath]);
915
+ expect(resultSub).toBe(true);
916
+ }
917
+
918
+ // Test allowed path access - use a file within the allowed directory
919
+ const allowedSubPath = 'nested';
920
+ const allowedFilePath = path.join(allowedPath, allowedSubPath, 'file.md');
921
+ expect(validateImportPath(allowedFilePath, basePath, [allowedPath])).toBe(
922
+ true,
923
+ );
924
+ });
925
+
926
+ it('should reject paths outside allowed directories', () => {
927
+ const basePath = path.resolve(testPath('base'));
928
+ const allowedPath = path.resolve(testPath('allowed'));
929
+ const forbiddenPath = path.resolve(testPath('forbidden'));
930
+
931
+ // Forbidden path should be blocked
932
+ expect(validateImportPath(forbiddenPath, basePath, [allowedPath])).toBe(
933
+ false,
934
+ );
935
+
936
+ // Relative path to forbidden directory should be blocked
937
+ const relativeToForbidden = path.relative(
938
+ basePath,
939
+ path.join(forbiddenPath, 'file.md'),
940
+ );
941
+ expect(
942
+ validateImportPath(relativeToForbidden, basePath, [allowedPath]),
943
+ ).toBe(false);
944
+
945
+ // Path that tries to escape the base directory should be blocked
946
+ const escapingPath = path.join('..', '..', 'sensitive', 'file.md');
947
+ expect(validateImportPath(escapingPath, basePath, [basePath])).toBe(
948
+ false,
949
+ );
950
+ });
951
+
952
+ it('should handle multiple allowed directories', () => {
953
+ const basePath = path.resolve(testPath('base'));
954
+ const allowed1 = path.resolve(testPath('allowed1'));
955
+ const allowed2 = path.resolve(testPath('allowed2'));
956
+
957
+ // File not in any allowed path
958
+ const otherPath = path.resolve(testPath('other', 'file.md'));
959
+ expect(
960
+ validateImportPath(otherPath, basePath, [allowed1, allowed2]),
961
+ ).toBe(false);
962
+
963
+ // File in first allowed path
964
+ const file1 = path.join(allowed1, 'nested', 'file.md');
965
+ expect(validateImportPath(file1, basePath, [allowed1, allowed2])).toBe(
966
+ true,
967
+ );
968
+
969
+ // File in second allowed path
970
+ const file2 = path.join(allowed2, 'nested', 'file.md');
971
+ expect(validateImportPath(file2, basePath, [allowed1, allowed2])).toBe(
972
+ true,
973
+ );
974
+
975
+ // Test with relative path to allowed directory
976
+ const relativeToAllowed1 = path.relative(basePath, file1);
977
+ expect(
978
+ validateImportPath(relativeToAllowed1, basePath, [allowed1, allowed2]),
979
+ ).toBe(true);
980
+ });
981
+
982
+ it('should handle relative paths correctly', () => {
983
+ const basePath = path.resolve(testPath('base'));
984
+ const parentPath = path.resolve(testPath('parent'));
985
+
986
+ // Current directory file access
987
+ expect(validateImportPath('file.md', basePath, [basePath])).toBe(true);
988
+
989
+ // Explicit current directory file access
990
+ expect(validateImportPath('./file.md', basePath, [basePath])).toBe(true);
991
+
992
+ // Parent directory access - should be blocked unless parent is in allowed paths
993
+ const parentFile = path.join(parentPath, 'file.md');
994
+ const relativeToParent = path.relative(basePath, parentFile);
995
+ expect(validateImportPath(relativeToParent, basePath, [basePath])).toBe(
996
+ false,
997
+ );
998
+
999
+ // Parent directory access when parent is in allowed paths
1000
+ expect(
1001
+ validateImportPath(relativeToParent, basePath, [basePath, parentPath]),
1002
+ ).toBe(true);
1003
+
1004
+ // Nested relative path
1005
+ const nestedPath = path.join('nested', 'sub', 'file.md');
1006
+ expect(validateImportPath(nestedPath, basePath, [basePath])).toBe(true);
1007
+ });
1008
+
1009
+ it('should handle absolute paths correctly', () => {
1010
+ const basePath = path.resolve(testPath('base'));
1011
+ const allowedPath = path.resolve(testPath('allowed'));
1012
+ const forbiddenPath = path.resolve(testPath('forbidden'));
1013
+
1014
+ // Allowed path should work - file directly in allowed directory
1015
+ const allowedFilePath = path.join(allowedPath, 'file.md');
1016
+ expect(validateImportPath(allowedFilePath, basePath, [allowedPath])).toBe(
1017
+ true,
1018
+ );
1019
+
1020
+ // Allowed path should work - file in subdirectory of allowed directory
1021
+ const allowedNestedPath = path.join(allowedPath, 'nested', 'file.md');
1022
+ expect(
1023
+ validateImportPath(allowedNestedPath, basePath, [allowedPath]),
1024
+ ).toBe(true);
1025
+
1026
+ // Forbidden path should be blocked
1027
+ const forbiddenFilePath = path.join(forbiddenPath, 'file.md');
1028
+ expect(
1029
+ validateImportPath(forbiddenFilePath, basePath, [allowedPath]),
1030
+ ).toBe(false);
1031
+
1032
+ // Relative path to allowed directory should work
1033
+ const relativeToAllowed = path.relative(basePath, allowedFilePath);
1034
+ expect(
1035
+ validateImportPath(relativeToAllowed, basePath, [allowedPath]),
1036
+ ).toBe(true);
1037
+
1038
+ // Path that resolves to the same file but via different relative segments
1039
+ const dotPath = path.join(
1040
+ '.',
1041
+ '..',
1042
+ path.basename(allowedPath),
1043
+ 'file.md',
1044
+ );
1045
+ expect(validateImportPath(dotPath, basePath, [allowedPath])).toBe(true);
1046
+ });
1047
+ });
1048
+ });
projects/ui/qwen-code/packages/core/src/utils/memoryImportProcessor.ts ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 * as path from 'path';
9
+ import { isSubpath } from './paths.js';
10
+ import { marked } from 'marked';
11
+
12
+ // Simple console logger for import processing
13
+ const logger = {
14
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
15
+ debug: (...args: any[]) =>
16
+ console.debug('[DEBUG] [ImportProcessor]', ...args),
17
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
18
+ warn: (...args: any[]) => console.warn('[WARN] [ImportProcessor]', ...args),
19
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
20
+ error: (...args: any[]) =>
21
+ console.error('[ERROR] [ImportProcessor]', ...args),
22
+ };
23
+
24
+ /**
25
+ * Interface for tracking import processing state to prevent circular imports
26
+ */
27
+ interface ImportState {
28
+ processedFiles: Set<string>;
29
+ maxDepth: number;
30
+ currentDepth: number;
31
+ currentFile?: string; // Track the current file being processed
32
+ }
33
+
34
+ /**
35
+ * Interface representing a file in the import tree
36
+ */
37
+ export interface MemoryFile {
38
+ path: string;
39
+ imports?: MemoryFile[]; // Direct imports, in the order they were imported
40
+ }
41
+
42
+ /**
43
+ * Result of processing imports
44
+ */
45
+ export interface ProcessImportsResult {
46
+ content: string;
47
+ importTree: MemoryFile;
48
+ }
49
+
50
+ // Helper to find the project root (looks for .git directory)
51
+ async function findProjectRoot(startDir: string): Promise<string> {
52
+ let currentDir = path.resolve(startDir);
53
+ while (true) {
54
+ const gitPath = path.join(currentDir, '.git');
55
+ try {
56
+ const stats = await fs.lstat(gitPath);
57
+ if (stats.isDirectory()) {
58
+ return currentDir;
59
+ }
60
+ } catch {
61
+ // .git not found, continue to parent
62
+ }
63
+ const parentDir = path.dirname(currentDir);
64
+ if (parentDir === currentDir) {
65
+ // Reached filesystem root
66
+ break;
67
+ }
68
+ currentDir = parentDir;
69
+ }
70
+ // Fallback to startDir if .git not found
71
+ return path.resolve(startDir);
72
+ }
73
+
74
+ // Add a type guard for error objects
75
+ function hasMessage(err: unknown): err is { message: string } {
76
+ return (
77
+ typeof err === 'object' &&
78
+ err !== null &&
79
+ 'message' in err &&
80
+ typeof (err as { message: unknown }).message === 'string'
81
+ );
82
+ }
83
+
84
+ // Helper to find all code block and inline code regions using marked
85
+ /**
86
+ * Finds all import statements in content without using regex
87
+ * @returns Array of {start, _end, path} objects for each import found
88
+ */
89
+ function findImports(
90
+ content: string,
91
+ ): Array<{ start: number; _end: number; path: string }> {
92
+ const imports: Array<{ start: number; _end: number; path: string }> = [];
93
+ let i = 0;
94
+ const len = content.length;
95
+
96
+ while (i < len) {
97
+ // Find next @ symbol
98
+ i = content.indexOf('@', i);
99
+ if (i === -1) break;
100
+
101
+ // Check if it's a word boundary (not part of another word)
102
+ if (i > 0 && !isWhitespace(content[i - 1])) {
103
+ i++;
104
+ continue;
105
+ }
106
+
107
+ // Find the end of the import path (whitespace or newline)
108
+ let j = i + 1;
109
+ while (
110
+ j < len &&
111
+ !isWhitespace(content[j]) &&
112
+ content[j] !== '\n' &&
113
+ content[j] !== '\r'
114
+ ) {
115
+ j++;
116
+ }
117
+
118
+ // Extract the path (everything after @)
119
+ const importPath = content.slice(i + 1, j);
120
+
121
+ // Basic validation (starts with ./ or / or letter)
122
+ if (
123
+ importPath.length > 0 &&
124
+ (importPath[0] === '.' ||
125
+ importPath[0] === '/' ||
126
+ isLetter(importPath[0]))
127
+ ) {
128
+ imports.push({
129
+ start: i,
130
+ _end: j,
131
+ path: importPath,
132
+ });
133
+ }
134
+
135
+ i = j + 1;
136
+ }
137
+
138
+ return imports;
139
+ }
140
+
141
+ function isWhitespace(char: string): boolean {
142
+ return char === ' ' || char === '\t' || char === '\n' || char === '\r';
143
+ }
144
+
145
+ function isLetter(char: string): boolean {
146
+ const code = char.charCodeAt(0);
147
+ return (
148
+ (code >= 65 && code <= 90) || // A-Z
149
+ (code >= 97 && code <= 122)
150
+ ); // a-z
151
+ }
152
+
153
+ function findCodeRegions(content: string): Array<[number, number]> {
154
+ const regions: Array<[number, number]> = [];
155
+ const tokens = marked.lexer(content);
156
+
157
+ // Map from raw content to a queue of its start indices in the original content.
158
+ const rawContentIndices = new Map<string, number[]>();
159
+
160
+ function walk(token: { type: string; raw: string; tokens?: unknown[] }) {
161
+ if (token.type === 'code' || token.type === 'codespan') {
162
+ if (!rawContentIndices.has(token.raw)) {
163
+ const indices: number[] = [];
164
+ let lastIndex = -1;
165
+ while ((lastIndex = content.indexOf(token.raw, lastIndex + 1)) !== -1) {
166
+ indices.push(lastIndex);
167
+ }
168
+ rawContentIndices.set(token.raw, indices);
169
+ }
170
+
171
+ const indices = rawContentIndices.get(token.raw);
172
+ if (indices && indices.length > 0) {
173
+ // Assume tokens are processed in order of appearance.
174
+ // Dequeue the next available index for this raw content.
175
+ const idx = indices.shift()!;
176
+ regions.push([idx, idx + token.raw.length]);
177
+ }
178
+ }
179
+
180
+ if ('tokens' in token && token.tokens) {
181
+ for (const child of token.tokens) {
182
+ walk(child as { type: string; raw: string; tokens?: unknown[] });
183
+ }
184
+ }
185
+ }
186
+
187
+ for (const token of tokens) {
188
+ walk(token);
189
+ }
190
+
191
+ return regions;
192
+ }
193
+
194
+ /**
195
+ * Processes import statements in QWEN.md content
196
+ * Supports @path/to/file syntax for importing content from other files
197
+ * @param content - The content to process for imports
198
+ * @param basePath - The directory path where the current file is located
199
+ * @param debugMode - Whether to enable debug logging
200
+ * @param importState - State tracking for circular import prevention
201
+ * @param projectRoot - The project root directory for allowed directories
202
+ * @param importFormat - The format of the import tree
203
+ * @returns Processed content with imports resolved and import tree
204
+ */
205
+ export async function processImports(
206
+ content: string,
207
+ basePath: string,
208
+ debugMode: boolean = false,
209
+ importState: ImportState = {
210
+ processedFiles: new Set(),
211
+ maxDepth: 5,
212
+ currentDepth: 0,
213
+ },
214
+ projectRoot?: string,
215
+ importFormat: 'flat' | 'tree' = 'tree',
216
+ ): Promise<ProcessImportsResult> {
217
+ if (!projectRoot) {
218
+ projectRoot = await findProjectRoot(basePath);
219
+ }
220
+
221
+ if (importState.currentDepth >= importState.maxDepth) {
222
+ if (debugMode) {
223
+ logger.warn(
224
+ `Maximum import depth (${importState.maxDepth}) reached. Stopping import processing.`,
225
+ );
226
+ }
227
+ return {
228
+ content,
229
+ importTree: { path: importState.currentFile || 'unknown' },
230
+ };
231
+ }
232
+
233
+ // --- FLAT FORMAT LOGIC ---
234
+ if (importFormat === 'flat') {
235
+ // Use a queue to process files in order of first encounter, and a set to avoid duplicates
236
+ const flatFiles: Array<{ path: string; content: string }> = [];
237
+ // Track processed files across the entire operation
238
+ const processedFiles = new Set<string>();
239
+
240
+ // Helper to recursively process imports
241
+ async function processFlat(
242
+ fileContent: string,
243
+ fileBasePath: string,
244
+ filePath: string,
245
+ depth: number,
246
+ ) {
247
+ // Normalize the file path to ensure consistent comparison
248
+ const normalizedPath = path.normalize(filePath);
249
+
250
+ // Skip if already processed
251
+ if (processedFiles.has(normalizedPath)) return;
252
+
253
+ // Mark as processed before processing to prevent infinite recursion
254
+ processedFiles.add(normalizedPath);
255
+
256
+ // Add this file to the flat list
257
+ flatFiles.push({ path: normalizedPath, content: fileContent });
258
+
259
+ // Find imports in this file
260
+ const codeRegions = findCodeRegions(fileContent);
261
+ const imports = findImports(fileContent);
262
+
263
+ // Process imports in reverse order to handle indices correctly
264
+ for (let i = imports.length - 1; i >= 0; i--) {
265
+ const { start, path: importPath } = imports[i];
266
+
267
+ // Skip if inside a code region
268
+ if (
269
+ codeRegions.some(
270
+ ([regionStart, regionEnd]) =>
271
+ start >= regionStart && start < regionEnd,
272
+ )
273
+ ) {
274
+ continue;
275
+ }
276
+
277
+ // Validate import path
278
+ if (
279
+ !validateImportPath(importPath, fileBasePath, [projectRoot || ''])
280
+ ) {
281
+ continue;
282
+ }
283
+
284
+ const fullPath = path.resolve(fileBasePath, importPath);
285
+ const normalizedFullPath = path.normalize(fullPath);
286
+
287
+ // Skip if already processed
288
+ if (processedFiles.has(normalizedFullPath)) continue;
289
+
290
+ try {
291
+ await fs.access(fullPath);
292
+ const importedContent = await fs.readFile(fullPath, 'utf-8');
293
+
294
+ // Process the imported file
295
+ await processFlat(
296
+ importedContent,
297
+ path.dirname(fullPath),
298
+ normalizedFullPath,
299
+ depth + 1,
300
+ );
301
+ } catch (error) {
302
+ if (debugMode) {
303
+ logger.warn(
304
+ `Failed to import ${fullPath}: ${hasMessage(error) ? error.message : 'Unknown error'}`,
305
+ );
306
+ }
307
+ // Continue with other imports even if one fails
308
+ }
309
+ }
310
+ }
311
+
312
+ // Start with the root file (current file)
313
+ const rootPath = path.normalize(
314
+ importState.currentFile || path.resolve(basePath),
315
+ );
316
+ await processFlat(content, basePath, rootPath, 0);
317
+
318
+ // Concatenate all unique files in order, Claude-style
319
+ const flatContent = flatFiles
320
+ .map(
321
+ (f) =>
322
+ `--- File: ${f.path} ---\n${f.content.trim()}\n--- End of File: ${f.path} ---`,
323
+ )
324
+ .join('\n\n');
325
+
326
+ return {
327
+ content: flatContent,
328
+ importTree: { path: rootPath }, // Tree not meaningful in flat mode
329
+ };
330
+ }
331
+
332
+ // --- TREE FORMAT LOGIC (existing) ---
333
+ const codeRegions = findCodeRegions(content);
334
+ let result = '';
335
+ let lastIndex = 0;
336
+ const imports: MemoryFile[] = [];
337
+ const importsList = findImports(content);
338
+
339
+ for (const { start, _end, path: importPath } of importsList) {
340
+ // Add content before this import
341
+ result += content.substring(lastIndex, start);
342
+ lastIndex = _end;
343
+
344
+ // Skip if inside a code region
345
+ if (codeRegions.some(([s, e]) => start >= s && start < e)) {
346
+ result += `@${importPath}`;
347
+ continue;
348
+ }
349
+ // Validate import path to prevent path traversal attacks
350
+ if (!validateImportPath(importPath, basePath, [projectRoot || ''])) {
351
+ result += `<!-- Import failed: ${importPath} - Path traversal attempt -->`;
352
+ continue;
353
+ }
354
+ const fullPath = path.resolve(basePath, importPath);
355
+ if (importState.processedFiles.has(fullPath)) {
356
+ result += `<!-- File already processed: ${importPath} -->`;
357
+ continue;
358
+ }
359
+ try {
360
+ await fs.access(fullPath);
361
+ const fileContent = await fs.readFile(fullPath, 'utf-8');
362
+ // Mark this file as processed for this import chain
363
+ const newImportState: ImportState = {
364
+ ...importState,
365
+ processedFiles: new Set(importState.processedFiles),
366
+ currentDepth: importState.currentDepth + 1,
367
+ currentFile: fullPath,
368
+ };
369
+ newImportState.processedFiles.add(fullPath);
370
+ const imported = await processImports(
371
+ fileContent,
372
+ path.dirname(fullPath),
373
+ debugMode,
374
+ newImportState,
375
+ projectRoot,
376
+ importFormat,
377
+ );
378
+ result += `<!-- Imported from: ${importPath} -->\n${imported.content}\n<!-- End of import from: ${importPath} -->`;
379
+ imports.push(imported.importTree);
380
+ } catch (err: unknown) {
381
+ let message = 'Unknown error';
382
+ if (hasMessage(err)) {
383
+ message = err.message;
384
+ } else if (typeof err === 'string') {
385
+ message = err;
386
+ }
387
+ logger.error(`Failed to import ${importPath}: ${message}`);
388
+ result += `<!-- Import failed: ${importPath} - ${message} -->`;
389
+ }
390
+ }
391
+ // Add any remaining content after the last match
392
+ result += content.substring(lastIndex);
393
+
394
+ return {
395
+ content: result,
396
+ importTree: {
397
+ path: importState.currentFile || 'unknown',
398
+ imports: imports.length > 0 ? imports : undefined,
399
+ },
400
+ };
401
+ }
402
+
403
+ export function validateImportPath(
404
+ importPath: string,
405
+ basePath: string,
406
+ allowedDirectories: string[],
407
+ ): boolean {
408
+ // Reject URLs
409
+ if (/^(file|https?):\/\//.test(importPath)) {
410
+ return false;
411
+ }
412
+
413
+ const resolvedPath = path.resolve(basePath, importPath);
414
+
415
+ return allowedDirectories.some((allowedDir) =>
416
+ isSubpath(allowedDir, resolvedPath),
417
+ );
418
+ }
projects/ui/qwen-code/packages/core/src/utils/messageInspectors.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Content } from '@google/genai';
8
+
9
+ export function isFunctionResponse(content: Content): boolean {
10
+ return (
11
+ content.role === 'user' &&
12
+ !!content.parts &&
13
+ content.parts.every((part) => !!part.functionResponse)
14
+ );
15
+ }
16
+
17
+ export function isFunctionCall(content: Content): boolean {
18
+ return (
19
+ content.role === 'model' &&
20
+ !!content.parts &&
21
+ content.parts.every((part) => !!part.functionCall)
22
+ );
23
+ }
projects/ui/qwen-code/packages/core/src/utils/nextSpeakerChecker.test.ts ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, Mock, afterEach } from 'vitest';
8
+ import { Content, GoogleGenAI, Models } from '@google/genai';
9
+ import { DEFAULT_GEMINI_FLASH_MODEL } from '../config/models.js';
10
+ import { GeminiClient } from '../core/client.js';
11
+ import { Config } from '../config/config.js';
12
+ import { checkNextSpeaker, NextSpeakerResponse } from './nextSpeakerChecker.js';
13
+ import { GeminiChat } from '../core/geminiChat.js';
14
+
15
+ // Mock GeminiClient and Config constructor
16
+ vi.mock('../core/client.js');
17
+ vi.mock('../config/config.js');
18
+
19
+ // Define mocks for GoogleGenAI and Models instances that will be used across tests
20
+ const mockModelsInstance = {
21
+ generateContent: vi.fn(),
22
+ generateContentStream: vi.fn(),
23
+ countTokens: vi.fn(),
24
+ embedContent: vi.fn(),
25
+ batchEmbedContents: vi.fn(),
26
+ } as unknown as Models;
27
+
28
+ const mockGoogleGenAIInstance = {
29
+ getGenerativeModel: vi.fn().mockReturnValue(mockModelsInstance),
30
+ // Add other methods of GoogleGenAI if they are directly used by GeminiChat constructor or its methods
31
+ } as unknown as GoogleGenAI;
32
+
33
+ vi.mock('@google/genai', async () => {
34
+ const actualGenAI =
35
+ await vi.importActual<typeof import('@google/genai')>('@google/genai');
36
+ return {
37
+ ...actualGenAI,
38
+ GoogleGenAI: vi.fn(() => mockGoogleGenAIInstance), // Mock constructor to return the predefined instance
39
+ // If Models is instantiated directly in GeminiChat, mock its constructor too
40
+ // For now, assuming Models instance is obtained via getGenerativeModel
41
+ };
42
+ });
43
+
44
+ describe('checkNextSpeaker', () => {
45
+ let chatInstance: GeminiChat;
46
+ let mockGeminiClient: GeminiClient;
47
+ let MockConfig: Mock;
48
+ const abortSignal = new AbortController().signal;
49
+
50
+ beforeEach(() => {
51
+ MockConfig = vi.mocked(Config);
52
+ const mockConfigInstance = new MockConfig(
53
+ 'test-api-key',
54
+ 'gemini-pro',
55
+ false,
56
+ '.',
57
+ false,
58
+ undefined,
59
+ false,
60
+ undefined,
61
+ undefined,
62
+ undefined,
63
+ );
64
+
65
+ mockGeminiClient = new GeminiClient(mockConfigInstance);
66
+
67
+ // Reset mocks before each test to ensure test isolation
68
+ vi.mocked(mockModelsInstance.generateContent).mockReset();
69
+ vi.mocked(mockModelsInstance.generateContentStream).mockReset();
70
+
71
+ // GeminiChat will receive the mocked instances via the mocked GoogleGenAI constructor
72
+ chatInstance = new GeminiChat(
73
+ mockConfigInstance,
74
+ mockModelsInstance, // This is the instance returned by mockGoogleGenAIInstance.getGenerativeModel
75
+ {},
76
+ [], // initial history
77
+ );
78
+
79
+ // Spy on getHistory for chatInstance
80
+ vi.spyOn(chatInstance, 'getHistory');
81
+ });
82
+
83
+ afterEach(() => {
84
+ vi.clearAllMocks();
85
+ });
86
+
87
+ it('should return null if history is empty', async () => {
88
+ (chatInstance.getHistory as Mock).mockReturnValue([]);
89
+ const result = await checkNextSpeaker(
90
+ chatInstance,
91
+ mockGeminiClient,
92
+ abortSignal,
93
+ );
94
+ expect(result).toBeNull();
95
+ expect(mockGeminiClient.generateJson).not.toHaveBeenCalled();
96
+ });
97
+
98
+ it('should return null if the last speaker was the user', async () => {
99
+ (chatInstance.getHistory as Mock).mockReturnValue([
100
+ { role: 'user', parts: [{ text: 'Hello' }] },
101
+ ] as Content[]);
102
+ const result = await checkNextSpeaker(
103
+ chatInstance,
104
+ mockGeminiClient,
105
+ abortSignal,
106
+ );
107
+ expect(result).toBeNull();
108
+ expect(mockGeminiClient.generateJson).not.toHaveBeenCalled();
109
+ });
110
+
111
+ it("should return { next_speaker: 'model' } when model intends to continue", async () => {
112
+ (chatInstance.getHistory as Mock).mockReturnValue([
113
+ { role: 'model', parts: [{ text: 'I will now do something.' }] },
114
+ ] as Content[]);
115
+ const mockApiResponse: NextSpeakerResponse = {
116
+ reasoning: 'Model stated it will do something.',
117
+ next_speaker: 'model',
118
+ };
119
+ (mockGeminiClient.generateJson as Mock).mockResolvedValue(mockApiResponse);
120
+
121
+ const result = await checkNextSpeaker(
122
+ chatInstance,
123
+ mockGeminiClient,
124
+ abortSignal,
125
+ );
126
+ expect(result).toEqual(mockApiResponse);
127
+ expect(mockGeminiClient.generateJson).toHaveBeenCalledTimes(1);
128
+ });
129
+
130
+ it("should return { next_speaker: 'user' } when model asks a question", async () => {
131
+ (chatInstance.getHistory as Mock).mockReturnValue([
132
+ { role: 'model', parts: [{ text: 'What would you like to do?' }] },
133
+ ] as Content[]);
134
+ const mockApiResponse: NextSpeakerResponse = {
135
+ reasoning: 'Model asked a question.',
136
+ next_speaker: 'user',
137
+ };
138
+ (mockGeminiClient.generateJson as Mock).mockResolvedValue(mockApiResponse);
139
+
140
+ const result = await checkNextSpeaker(
141
+ chatInstance,
142
+ mockGeminiClient,
143
+ abortSignal,
144
+ );
145
+ expect(result).toEqual(mockApiResponse);
146
+ });
147
+
148
+ it("should return { next_speaker: 'user' } when model makes a statement", async () => {
149
+ (chatInstance.getHistory as Mock).mockReturnValue([
150
+ { role: 'model', parts: [{ text: 'This is a statement.' }] },
151
+ ] as Content[]);
152
+ const mockApiResponse: NextSpeakerResponse = {
153
+ reasoning: 'Model made a statement, awaiting user input.',
154
+ next_speaker: 'user',
155
+ };
156
+ (mockGeminiClient.generateJson as Mock).mockResolvedValue(mockApiResponse);
157
+
158
+ const result = await checkNextSpeaker(
159
+ chatInstance,
160
+ mockGeminiClient,
161
+ abortSignal,
162
+ );
163
+ expect(result).toEqual(mockApiResponse);
164
+ });
165
+
166
+ it('should return null if geminiClient.generateJson throws an error', async () => {
167
+ const consoleWarnSpy = vi
168
+ .spyOn(console, 'warn')
169
+ .mockImplementation(() => {});
170
+ (chatInstance.getHistory as Mock).mockReturnValue([
171
+ { role: 'model', parts: [{ text: 'Some model output.' }] },
172
+ ] as Content[]);
173
+ (mockGeminiClient.generateJson as Mock).mockRejectedValue(
174
+ new Error('API Error'),
175
+ );
176
+
177
+ const result = await checkNextSpeaker(
178
+ chatInstance,
179
+ mockGeminiClient,
180
+ abortSignal,
181
+ );
182
+ expect(result).toBeNull();
183
+ consoleWarnSpy.mockRestore();
184
+ });
185
+
186
+ it('should return null if geminiClient.generateJson returns invalid JSON (missing next_speaker)', async () => {
187
+ (chatInstance.getHistory as Mock).mockReturnValue([
188
+ { role: 'model', parts: [{ text: 'Some model output.' }] },
189
+ ] as Content[]);
190
+ (mockGeminiClient.generateJson as Mock).mockResolvedValue({
191
+ reasoning: 'This is incomplete.',
192
+ } as unknown as NextSpeakerResponse); // Type assertion to simulate invalid response
193
+
194
+ const result = await checkNextSpeaker(
195
+ chatInstance,
196
+ mockGeminiClient,
197
+ abortSignal,
198
+ );
199
+ expect(result).toBeNull();
200
+ });
201
+
202
+ it('should return null if geminiClient.generateJson returns a non-string next_speaker', async () => {
203
+ (chatInstance.getHistory as Mock).mockReturnValue([
204
+ { role: 'model', parts: [{ text: 'Some model output.' }] },
205
+ ] as Content[]);
206
+ (mockGeminiClient.generateJson as Mock).mockResolvedValue({
207
+ reasoning: 'Model made a statement, awaiting user input.',
208
+ next_speaker: 123, // Invalid type
209
+ } as unknown as NextSpeakerResponse);
210
+
211
+ const result = await checkNextSpeaker(
212
+ chatInstance,
213
+ mockGeminiClient,
214
+ abortSignal,
215
+ );
216
+ expect(result).toBeNull();
217
+ });
218
+
219
+ it('should return null if geminiClient.generateJson returns an invalid next_speaker string value', async () => {
220
+ (chatInstance.getHistory as Mock).mockReturnValue([
221
+ { role: 'model', parts: [{ text: 'Some model output.' }] },
222
+ ] as Content[]);
223
+ (mockGeminiClient.generateJson as Mock).mockResolvedValue({
224
+ reasoning: 'Model made a statement, awaiting user input.',
225
+ next_speaker: 'neither', // Invalid enum value
226
+ } as unknown as NextSpeakerResponse);
227
+
228
+ const result = await checkNextSpeaker(
229
+ chatInstance,
230
+ mockGeminiClient,
231
+ abortSignal,
232
+ );
233
+ expect(result).toBeNull();
234
+ });
235
+
236
+ it('should call generateJson with DEFAULT_GEMINI_FLASH_MODEL', async () => {
237
+ (chatInstance.getHistory as Mock).mockReturnValue([
238
+ { role: 'model', parts: [{ text: 'Some model output.' }] },
239
+ ] as Content[]);
240
+ const mockApiResponse: NextSpeakerResponse = {
241
+ reasoning: 'Model made a statement, awaiting user input.',
242
+ next_speaker: 'user',
243
+ };
244
+ (mockGeminiClient.generateJson as Mock).mockResolvedValue(mockApiResponse);
245
+
246
+ await checkNextSpeaker(chatInstance, mockGeminiClient, abortSignal);
247
+
248
+ expect(mockGeminiClient.generateJson).toHaveBeenCalled();
249
+ const generateJsonCall = (mockGeminiClient.generateJson as Mock).mock
250
+ .calls[0];
251
+ expect(generateJsonCall[3]).toBe(DEFAULT_GEMINI_FLASH_MODEL);
252
+ });
253
+ });
projects/ui/qwen-code/packages/core/src/utils/nextSpeakerChecker.ts ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Content } from '@google/genai';
8
+ import { DEFAULT_GEMINI_FLASH_MODEL } from '../config/models.js';
9
+ import { GeminiClient } from '../core/client.js';
10
+ import { GeminiChat } from '../core/geminiChat.js';
11
+ import { isFunctionResponse } from './messageInspectors.js';
12
+
13
+ const CHECK_PROMPT = `Analyze *only* the content and structure of your immediately preceding response (your last turn in the conversation history). Based *strictly* on that response, determine who should logically speak next: the 'user' or the 'model' (you).
14
+ **Decision Rules (apply in order):**
15
+ 1. **Model Continues:** If your last response explicitly states an immediate next action *you* intend to take (e.g., "Next, I will...", "Now I'll process...", "Moving on to analyze...", indicates an intended tool call that didn't execute), OR if the response seems clearly incomplete (cut off mid-thought without a natural conclusion), then the **'model'** should speak next.
16
+ 2. **Question to User:** If your last response ends with a direct question specifically addressed *to the user*, then the **'user'** should speak next.
17
+ 3. **Waiting for User:** If your last response completed a thought, statement, or task *and* does not meet the criteria for Rule 1 (Model Continues) or Rule 2 (Question to User), it implies a pause expecting user input or reaction. In this case, the **'user'** should speak next.`;
18
+
19
+ const RESPONSE_SCHEMA: Record<string, unknown> = {
20
+ type: 'object',
21
+ properties: {
22
+ reasoning: {
23
+ type: 'string',
24
+ description:
25
+ "Brief explanation justifying the 'next_speaker' choice based *strictly* on the applicable rule and the content/structure of the preceding turn.",
26
+ },
27
+ next_speaker: {
28
+ type: 'string',
29
+ enum: ['user', 'model'],
30
+ description:
31
+ 'Who should speak next based *only* on the preceding turn and the decision rules',
32
+ },
33
+ },
34
+ required: ['reasoning', 'next_speaker'],
35
+ };
36
+
37
+ export interface NextSpeakerResponse {
38
+ reasoning: string;
39
+ next_speaker: 'user' | 'model';
40
+ }
41
+
42
+ export async function checkNextSpeaker(
43
+ chat: GeminiChat,
44
+ geminiClient: GeminiClient,
45
+ abortSignal: AbortSignal,
46
+ ): Promise<NextSpeakerResponse | null> {
47
+ // We need to capture the curated history because there are many moments when the model will return invalid turns
48
+ // that when passed back up to the endpoint will break subsequent calls. An example of this is when the model decides
49
+ // to respond with an empty part collection if you were to send that message back to the server it will respond with
50
+ // a 400 indicating that model part collections MUST have content.
51
+ const curatedHistory = chat.getHistory(/* curated */ true);
52
+
53
+ // Ensure there's a model response to analyze
54
+ if (curatedHistory.length === 0) {
55
+ // Cannot determine next speaker if history is empty.
56
+ return null;
57
+ }
58
+
59
+ const comprehensiveHistory = chat.getHistory();
60
+ // If comprehensiveHistory is empty, there is no last message to check.
61
+ // This case should ideally be caught by the curatedHistory.length check earlier,
62
+ // but as a safeguard:
63
+ if (comprehensiveHistory.length === 0) {
64
+ return null;
65
+ }
66
+ const lastComprehensiveMessage =
67
+ comprehensiveHistory[comprehensiveHistory.length - 1];
68
+
69
+ // If the last message is a user message containing only function_responses,
70
+ // then the model should speak next.
71
+ if (
72
+ lastComprehensiveMessage &&
73
+ isFunctionResponse(lastComprehensiveMessage)
74
+ ) {
75
+ return {
76
+ reasoning:
77
+ 'The last message was a function response, so the model should speak next.',
78
+ next_speaker: 'model',
79
+ };
80
+ }
81
+
82
+ if (
83
+ lastComprehensiveMessage &&
84
+ lastComprehensiveMessage.role === 'model' &&
85
+ lastComprehensiveMessage.parts &&
86
+ lastComprehensiveMessage.parts.length === 0
87
+ ) {
88
+ lastComprehensiveMessage.parts.push({ text: '' });
89
+ return {
90
+ reasoning:
91
+ 'The last message was a filler model message with no content (nothing for user to act on), model should speak next.',
92
+ next_speaker: 'model',
93
+ };
94
+ }
95
+
96
+ // Things checked out. Let's proceed to potentially making an LLM request.
97
+
98
+ const lastMessage = curatedHistory[curatedHistory.length - 1];
99
+ if (!lastMessage || lastMessage.role !== 'model') {
100
+ // Cannot determine next speaker if the last turn wasn't from the model
101
+ // or if history is empty.
102
+ return null;
103
+ }
104
+
105
+ const contents: Content[] = [
106
+ ...curatedHistory,
107
+ { role: 'user', parts: [{ text: CHECK_PROMPT }] },
108
+ ];
109
+
110
+ try {
111
+ const parsedResponse = (await geminiClient.generateJson(
112
+ contents,
113
+ RESPONSE_SCHEMA,
114
+ abortSignal,
115
+ DEFAULT_GEMINI_FLASH_MODEL,
116
+ )) as unknown as NextSpeakerResponse;
117
+
118
+ if (
119
+ parsedResponse &&
120
+ parsedResponse.next_speaker &&
121
+ ['user', 'model'].includes(parsedResponse.next_speaker)
122
+ ) {
123
+ return parsedResponse;
124
+ }
125
+ return null;
126
+ } catch (error) {
127
+ console.warn(
128
+ 'Failed to talk to Gemini endpoint when seeing if conversation should continue.',
129
+ error,
130
+ );
131
+ return null;
132
+ }
133
+ }
projects/ui/qwen-code/packages/core/src/utils/openaiLogger.ts ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as path from 'node:path';
8
+ import { promises as fs } from 'node:fs';
9
+ import { v4 as uuidv4 } from 'uuid';
10
+ import * as os from 'os';
11
+
12
+ /**
13
+ * Logger specifically for OpenAI API requests and responses
14
+ */
15
+ export class OpenAILogger {
16
+ private logDir: string;
17
+ private initialized: boolean = false;
18
+
19
+ /**
20
+ * Creates a new OpenAI logger
21
+ * @param customLogDir Optional custom log directory path
22
+ */
23
+ constructor(customLogDir?: string) {
24
+ this.logDir = customLogDir || path.join(process.cwd(), 'logs', 'openai');
25
+ }
26
+
27
+ /**
28
+ * Initialize the logger by creating the log directory if it doesn't exist
29
+ */
30
+ async initialize(): Promise<void> {
31
+ if (this.initialized) return;
32
+
33
+ try {
34
+ await fs.mkdir(this.logDir, { recursive: true });
35
+ this.initialized = true;
36
+ } catch (error) {
37
+ console.error('Failed to initialize OpenAI logger:', error);
38
+ throw new Error(`Failed to initialize OpenAI logger: ${error}`);
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Logs an OpenAI API request and its response
44
+ * @param request The request sent to OpenAI
45
+ * @param response The response received from OpenAI
46
+ * @param error Optional error if the request failed
47
+ * @returns The file path where the log was written
48
+ */
49
+ async logInteraction(
50
+ request: unknown,
51
+ response?: unknown,
52
+ error?: Error,
53
+ ): Promise<string> {
54
+ if (!this.initialized) {
55
+ await this.initialize();
56
+ }
57
+
58
+ const timestamp = new Date().toISOString().replace(/:/g, '-');
59
+ const id = uuidv4().slice(0, 8);
60
+ const filename = `openai-${timestamp}-${id}.json`;
61
+ const filePath = path.join(this.logDir, filename);
62
+
63
+ const logData = {
64
+ timestamp: new Date().toISOString(),
65
+ request,
66
+ response: response || null,
67
+ error: error
68
+ ? {
69
+ message: error.message,
70
+ stack: error.stack,
71
+ }
72
+ : null,
73
+ system: {
74
+ hostname: os.hostname(),
75
+ platform: os.platform(),
76
+ release: os.release(),
77
+ nodeVersion: process.version,
78
+ },
79
+ };
80
+
81
+ try {
82
+ await fs.writeFile(filePath, JSON.stringify(logData, null, 2), 'utf-8');
83
+ return filePath;
84
+ } catch (writeError) {
85
+ console.error('Failed to write OpenAI log file:', writeError);
86
+ throw new Error(`Failed to write OpenAI log file: ${writeError}`);
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Get all logged interactions
92
+ * @param limit Optional limit on the number of log files to return (sorted by most recent first)
93
+ * @returns Array of log file paths
94
+ */
95
+ async getLogFiles(limit?: number): Promise<string[]> {
96
+ if (!this.initialized) {
97
+ await this.initialize();
98
+ }
99
+
100
+ try {
101
+ const files = await fs.readdir(this.logDir);
102
+ const logFiles = files
103
+ .filter((file) => file.startsWith('openai-') && file.endsWith('.json'))
104
+ .map((file) => path.join(this.logDir, file))
105
+ .sort()
106
+ .reverse();
107
+
108
+ return limit ? logFiles.slice(0, limit) : logFiles;
109
+ } catch (error) {
110
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
111
+ return [];
112
+ }
113
+ console.error('Failed to read OpenAI log directory:', error);
114
+ return [];
115
+ }
116
+ }
117
+
118
+ /**
119
+ * Read a specific log file
120
+ * @param filePath The path to the log file
121
+ * @returns The log file content
122
+ */
123
+ async readLogFile(filePath: string): Promise<unknown> {
124
+ try {
125
+ const content = await fs.readFile(filePath, 'utf-8');
126
+ return JSON.parse(content);
127
+ } catch (error) {
128
+ console.error(`Failed to read log file ${filePath}:`, error);
129
+ throw new Error(`Failed to read log file: ${error}`);
130
+ }
131
+ }
132
+ }
133
+
134
+ // Create a singleton instance for easy import
135
+ export const openaiLogger = new OpenAILogger();
projects/ui/qwen-code/packages/core/src/utils/partUtils.test.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 { describe, it, expect } from 'vitest';
8
+ import { partToString, getResponseText } from './partUtils.js';
9
+ import { GenerateContentResponse, Part } from '@google/genai';
10
+
11
+ const mockResponse = (
12
+ parts?: Array<{ text?: string; functionCall?: unknown }>,
13
+ ): GenerateContentResponse => ({
14
+ candidates: parts
15
+ ? [{ content: { parts: parts as Part[], role: 'model' }, index: 0 }]
16
+ : [],
17
+ promptFeedback: { safetyRatings: [] },
18
+ text: undefined,
19
+ data: undefined,
20
+ functionCalls: undefined,
21
+ executableCode: undefined,
22
+ codeExecutionResult: undefined,
23
+ });
24
+
25
+ describe('partUtils', () => {
26
+ describe('partToString (default behavior)', () => {
27
+ it('should return empty string for undefined or null', () => {
28
+ // @ts-expect-error Testing invalid input
29
+ expect(partToString(undefined)).toBe('');
30
+ // @ts-expect-error Testing invalid input
31
+ expect(partToString(null)).toBe('');
32
+ });
33
+
34
+ it('should return string input unchanged', () => {
35
+ expect(partToString('hello')).toBe('hello');
36
+ });
37
+
38
+ it('should concatenate strings from an array', () => {
39
+ expect(partToString(['a', 'b'])).toBe('ab');
40
+ });
41
+
42
+ it('should return text property when provided a text part', () => {
43
+ expect(partToString({ text: 'hi' })).toBe('hi');
44
+ });
45
+
46
+ it('should return empty string for non-text parts', () => {
47
+ const part: Part = { inlineData: { mimeType: 'image/png', data: '' } };
48
+ expect(partToString(part)).toBe('');
49
+ const part2: Part = { functionCall: { name: 'test' } };
50
+ expect(partToString(part2)).toBe('');
51
+ });
52
+ });
53
+
54
+ describe('partToString (verbose)', () => {
55
+ const verboseOptions = { verbose: true };
56
+
57
+ it('should return empty string for undefined or null', () => {
58
+ // @ts-expect-error Testing invalid input
59
+ expect(partToString(undefined, verboseOptions)).toBe('');
60
+ // @ts-expect-error Testing invalid input
61
+ expect(partToString(null, verboseOptions)).toBe('');
62
+ });
63
+
64
+ it('should return string input unchanged', () => {
65
+ expect(partToString('hello', verboseOptions)).toBe('hello');
66
+ });
67
+
68
+ it('should join parts if the value is an array', () => {
69
+ const parts = ['hello', { text: ' world' }];
70
+ expect(partToString(parts, verboseOptions)).toBe('hello world');
71
+ });
72
+
73
+ it('should return the text property if the part is an object with text', () => {
74
+ const part: Part = { text: 'hello world' };
75
+ expect(partToString(part, verboseOptions)).toBe('hello world');
76
+ });
77
+
78
+ it('should return descriptive string for videoMetadata part', () => {
79
+ const part = { videoMetadata: {} } as Part;
80
+ expect(partToString(part, verboseOptions)).toBe('[Video Metadata]');
81
+ });
82
+
83
+ it('should return descriptive string for thought part', () => {
84
+ const part = { thought: 'thinking' } as unknown as Part;
85
+ expect(partToString(part, verboseOptions)).toBe('[Thought: thinking]');
86
+ });
87
+
88
+ it('should return descriptive string for codeExecutionResult part', () => {
89
+ const part = { codeExecutionResult: {} } as Part;
90
+ expect(partToString(part, verboseOptions)).toBe(
91
+ '[Code Execution Result]',
92
+ );
93
+ });
94
+
95
+ it('should return descriptive string for executableCode part', () => {
96
+ const part = { executableCode: {} } as Part;
97
+ expect(partToString(part, verboseOptions)).toBe('[Executable Code]');
98
+ });
99
+
100
+ it('should return descriptive string for fileData part', () => {
101
+ const part = { fileData: {} } as Part;
102
+ expect(partToString(part, verboseOptions)).toBe('[File Data]');
103
+ });
104
+
105
+ it('should return descriptive string for functionCall part', () => {
106
+ const part = { functionCall: { name: 'myFunction' } } as Part;
107
+ expect(partToString(part, verboseOptions)).toBe(
108
+ '[Function Call: myFunction]',
109
+ );
110
+ });
111
+
112
+ it('should return descriptive string for functionResponse part', () => {
113
+ const part = { functionResponse: { name: 'myFunction' } } as Part;
114
+ expect(partToString(part, verboseOptions)).toBe(
115
+ '[Function Response: myFunction]',
116
+ );
117
+ });
118
+
119
+ it('should return descriptive string for inlineData part', () => {
120
+ const part = { inlineData: { mimeType: 'image/png', data: '' } } as Part;
121
+ expect(partToString(part, verboseOptions)).toBe('<image/png>');
122
+ });
123
+
124
+ it('should return an empty string for an unknown part type', () => {
125
+ const part: Part = {};
126
+ expect(partToString(part, verboseOptions)).toBe('');
127
+ });
128
+
129
+ it('should handle complex nested arrays with various part types', () => {
130
+ const parts = [
131
+ 'start ',
132
+ { text: 'middle' },
133
+ [
134
+ { functionCall: { name: 'func1' } },
135
+ ' end',
136
+ { inlineData: { mimeType: 'audio/mp3', data: '' } },
137
+ ],
138
+ ];
139
+ expect(partToString(parts as Part, verboseOptions)).toBe(
140
+ 'start middle[Function Call: func1] end<audio/mp3>',
141
+ );
142
+ });
143
+ });
144
+
145
+ describe('getResponseText', () => {
146
+ it('should return null when no candidates exist', () => {
147
+ const response = mockResponse(undefined);
148
+ expect(getResponseText(response)).toBeNull();
149
+ });
150
+
151
+ it('should return concatenated text from first candidate', () => {
152
+ const result = mockResponse([{ text: 'a' }, { text: 'b' }]);
153
+ expect(getResponseText(result)).toBe('ab');
154
+ });
155
+
156
+ it('should ignore parts without text', () => {
157
+ const result = mockResponse([{ functionCall: {} }, { text: 'hello' }]);
158
+ expect(getResponseText(result)).toBe('hello');
159
+ });
160
+
161
+ it('should return null when candidate has no parts', () => {
162
+ const result = mockResponse([]);
163
+ expect(getResponseText(result)).toBeNull();
164
+ });
165
+ });
166
+ });
projects/ui/qwen-code/packages/core/src/utils/partUtils.ts ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { GenerateContentResponse, PartListUnion, Part } from '@google/genai';
8
+
9
+ /**
10
+ * Converts a PartListUnion into a string.
11
+ * If verbose is true, includes summary representations of non-text parts.
12
+ */
13
+ export function partToString(
14
+ value: PartListUnion,
15
+ options?: { verbose?: boolean },
16
+ ): string {
17
+ if (!value) {
18
+ return '';
19
+ }
20
+ if (typeof value === 'string') {
21
+ return value;
22
+ }
23
+ if (Array.isArray(value)) {
24
+ return value.map((part) => partToString(part, options)).join('');
25
+ }
26
+
27
+ // Cast to Part, assuming it might contain project-specific fields
28
+ const part = value as Part & {
29
+ videoMetadata?: unknown;
30
+ thought?: string;
31
+ codeExecutionResult?: unknown;
32
+ executableCode?: unknown;
33
+ };
34
+
35
+ if (options?.verbose) {
36
+ if (part.videoMetadata !== undefined) {
37
+ return `[Video Metadata]`;
38
+ }
39
+ if (part.thought !== undefined) {
40
+ return `[Thought: ${part.thought}]`;
41
+ }
42
+ if (part.codeExecutionResult !== undefined) {
43
+ return `[Code Execution Result]`;
44
+ }
45
+ if (part.executableCode !== undefined) {
46
+ return `[Executable Code]`;
47
+ }
48
+
49
+ // Standard Part fields
50
+ if (part.fileData !== undefined) {
51
+ return `[File Data]`;
52
+ }
53
+ if (part.functionCall !== undefined) {
54
+ return `[Function Call: ${part.functionCall.name}]`;
55
+ }
56
+ if (part.functionResponse !== undefined) {
57
+ return `[Function Response: ${part.functionResponse.name}]`;
58
+ }
59
+ if (part.inlineData !== undefined) {
60
+ return `<${part.inlineData.mimeType}>`;
61
+ }
62
+ }
63
+
64
+ return part.text ?? '';
65
+ }
66
+
67
+ export function getResponseText(
68
+ response: GenerateContentResponse,
69
+ ): string | null {
70
+ if (response.candidates && response.candidates.length > 0) {
71
+ const candidate = response.candidates[0];
72
+
73
+ if (
74
+ candidate.content &&
75
+ candidate.content.parts &&
76
+ candidate.content.parts.length > 0
77
+ ) {
78
+ return candidate.content.parts
79
+ .filter((part) => part.text)
80
+ .map((part) => part.text)
81
+ .join('');
82
+ }
83
+ }
84
+ return null;
85
+ }
projects/ui/qwen-code/packages/core/src/utils/paths.test.ts ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
8
+ import { escapePath, unescapePath, isSubpath } from './paths.js';
9
+
10
+ describe('escapePath', () => {
11
+ it('should escape spaces', () => {
12
+ expect(escapePath('my file.txt')).toBe('my\\ file.txt');
13
+ });
14
+
15
+ it('should escape tabs', () => {
16
+ expect(escapePath('file\twith\ttabs.txt')).toBe('file\\\twith\\\ttabs.txt');
17
+ });
18
+
19
+ it('should escape parentheses', () => {
20
+ expect(escapePath('file(1).txt')).toBe('file\\(1\\).txt');
21
+ });
22
+
23
+ it('should escape square brackets', () => {
24
+ expect(escapePath('file[backup].txt')).toBe('file\\[backup\\].txt');
25
+ });
26
+
27
+ it('should escape curly braces', () => {
28
+ expect(escapePath('file{temp}.txt')).toBe('file\\{temp\\}.txt');
29
+ });
30
+
31
+ it('should escape semicolons', () => {
32
+ expect(escapePath('file;name.txt')).toBe('file\\;name.txt');
33
+ });
34
+
35
+ it('should escape ampersands', () => {
36
+ expect(escapePath('file&name.txt')).toBe('file\\&name.txt');
37
+ });
38
+
39
+ it('should escape pipes', () => {
40
+ expect(escapePath('file|name.txt')).toBe('file\\|name.txt');
41
+ });
42
+
43
+ it('should escape asterisks', () => {
44
+ expect(escapePath('file*.txt')).toBe('file\\*.txt');
45
+ });
46
+
47
+ it('should escape question marks', () => {
48
+ expect(escapePath('file?.txt')).toBe('file\\?.txt');
49
+ });
50
+
51
+ it('should escape dollar signs', () => {
52
+ expect(escapePath('file$name.txt')).toBe('file\\$name.txt');
53
+ });
54
+
55
+ it('should escape backticks', () => {
56
+ expect(escapePath('file`name.txt')).toBe('file\\`name.txt');
57
+ });
58
+
59
+ it('should escape single quotes', () => {
60
+ expect(escapePath("file'name.txt")).toBe("file\\'name.txt");
61
+ });
62
+
63
+ it('should escape double quotes', () => {
64
+ expect(escapePath('file"name.txt')).toBe('file\\"name.txt');
65
+ });
66
+
67
+ it('should escape hash symbols', () => {
68
+ expect(escapePath('file#name.txt')).toBe('file\\#name.txt');
69
+ });
70
+
71
+ it('should escape exclamation marks', () => {
72
+ expect(escapePath('file!name.txt')).toBe('file\\!name.txt');
73
+ });
74
+
75
+ it('should escape tildes', () => {
76
+ expect(escapePath('file~name.txt')).toBe('file\\~name.txt');
77
+ });
78
+
79
+ it('should escape less than and greater than signs', () => {
80
+ expect(escapePath('file<name>.txt')).toBe('file\\<name\\>.txt');
81
+ });
82
+
83
+ it('should handle multiple special characters', () => {
84
+ expect(escapePath('my file (backup) [v1.2].txt')).toBe(
85
+ 'my\\ file\\ \\(backup\\)\\ \\[v1.2\\].txt',
86
+ );
87
+ });
88
+
89
+ it('should not double-escape already escaped characters', () => {
90
+ expect(escapePath('my\\ file.txt')).toBe('my\\ file.txt');
91
+ expect(escapePath('file\\(name\\).txt')).toBe('file\\(name\\).txt');
92
+ });
93
+
94
+ it('should handle escaped backslashes correctly', () => {
95
+ // Double backslash (escaped backslash) followed by space should escape the space
96
+ expect(escapePath('path\\\\ file.txt')).toBe('path\\\\\\ file.txt');
97
+ // Triple backslash (escaped backslash + escaping backslash) followed by space should not double-escape
98
+ expect(escapePath('path\\\\\\ file.txt')).toBe('path\\\\\\ file.txt');
99
+ // Quadruple backslash (two escaped backslashes) followed by space should escape the space
100
+ expect(escapePath('path\\\\\\\\ file.txt')).toBe('path\\\\\\\\\\ file.txt');
101
+ });
102
+
103
+ it('should handle complex escaped backslash scenarios', () => {
104
+ // Escaped backslash before special character that needs escaping
105
+ expect(escapePath('file\\\\(test).txt')).toBe('file\\\\\\(test\\).txt');
106
+ // Multiple escaped backslashes
107
+ expect(escapePath('path\\\\\\\\with space.txt')).toBe(
108
+ 'path\\\\\\\\with\\ space.txt',
109
+ );
110
+ });
111
+
112
+ it('should handle paths without special characters', () => {
113
+ expect(escapePath('normalfile.txt')).toBe('normalfile.txt');
114
+ expect(escapePath('path/to/normalfile.txt')).toBe('path/to/normalfile.txt');
115
+ });
116
+
117
+ it('should handle complex real-world examples', () => {
118
+ expect(escapePath('My Documents/Project (2024)/file [backup].txt')).toBe(
119
+ 'My\\ Documents/Project\\ \\(2024\\)/file\\ \\[backup\\].txt',
120
+ );
121
+ expect(escapePath('file with $special &chars!.txt')).toBe(
122
+ 'file\\ with\\ \\$special\\ \\&chars\\!.txt',
123
+ );
124
+ });
125
+
126
+ it('should handle empty strings', () => {
127
+ expect(escapePath('')).toBe('');
128
+ });
129
+
130
+ it('should handle paths with only special characters', () => {
131
+ expect(escapePath(' ()[]{};&|*?$`\'"#!~<>')).toBe(
132
+ '\\ \\(\\)\\[\\]\\{\\}\\;\\&\\|\\*\\?\\$\\`\\\'\\"\\#\\!\\~\\<\\>',
133
+ );
134
+ });
135
+ });
136
+
137
+ describe('unescapePath', () => {
138
+ it('should unescape spaces', () => {
139
+ expect(unescapePath('my\\ file.txt')).toBe('my file.txt');
140
+ });
141
+
142
+ it('should unescape tabs', () => {
143
+ expect(unescapePath('file\\\twith\\\ttabs.txt')).toBe(
144
+ 'file\twith\ttabs.txt',
145
+ );
146
+ });
147
+
148
+ it('should unescape parentheses', () => {
149
+ expect(unescapePath('file\\(1\\).txt')).toBe('file(1).txt');
150
+ });
151
+
152
+ it('should unescape square brackets', () => {
153
+ expect(unescapePath('file\\[backup\\].txt')).toBe('file[backup].txt');
154
+ });
155
+
156
+ it('should unescape curly braces', () => {
157
+ expect(unescapePath('file\\{temp\\}.txt')).toBe('file{temp}.txt');
158
+ });
159
+
160
+ it('should unescape multiple special characters', () => {
161
+ expect(unescapePath('my\\ file\\ \\(backup\\)\\ \\[v1.2\\].txt')).toBe(
162
+ 'my file (backup) [v1.2].txt',
163
+ );
164
+ });
165
+
166
+ it('should handle paths without escaped characters', () => {
167
+ expect(unescapePath('normalfile.txt')).toBe('normalfile.txt');
168
+ expect(unescapePath('path/to/normalfile.txt')).toBe(
169
+ 'path/to/normalfile.txt',
170
+ );
171
+ });
172
+
173
+ it('should handle all special characters', () => {
174
+ expect(
175
+ unescapePath(
176
+ '\\ \\(\\)\\[\\]\\{\\}\\;\\&\\|\\*\\?\\$\\`\\\'\\"\\#\\!\\~\\<\\>',
177
+ ),
178
+ ).toBe(' ()[]{};&|*?$`\'"#!~<>');
179
+ });
180
+
181
+ it('should be the inverse of escapePath', () => {
182
+ const testCases = [
183
+ 'my file.txt',
184
+ 'file(1).txt',
185
+ 'file[backup].txt',
186
+ 'My Documents/Project (2024)/file [backup].txt',
187
+ 'file with $special &chars!.txt',
188
+ ' ()[]{};&|*?$`\'"#!~<>',
189
+ 'file\twith\ttabs.txt',
190
+ ];
191
+
192
+ testCases.forEach((testCase) => {
193
+ expect(unescapePath(escapePath(testCase))).toBe(testCase);
194
+ });
195
+ });
196
+
197
+ it('should handle empty strings', () => {
198
+ expect(unescapePath('')).toBe('');
199
+ });
200
+
201
+ it('should not affect backslashes not followed by special characters', () => {
202
+ expect(unescapePath('file\\name.txt')).toBe('file\\name.txt');
203
+ expect(unescapePath('path\\to\\file.txt')).toBe('path\\to\\file.txt');
204
+ });
205
+
206
+ it('should handle escaped backslashes in unescaping', () => {
207
+ // Should correctly unescape when there are escaped backslashes
208
+ expect(unescapePath('path\\\\\\ file.txt')).toBe('path\\\\ file.txt');
209
+ expect(unescapePath('path\\\\\\\\\\ file.txt')).toBe(
210
+ 'path\\\\\\\\ file.txt',
211
+ );
212
+ expect(unescapePath('file\\\\\\(test\\).txt')).toBe('file\\\\(test).txt');
213
+ });
214
+ });
215
+
216
+ describe('isSubpath', () => {
217
+ it('should return true for a direct subpath', () => {
218
+ expect(isSubpath('/a/b', '/a/b/c')).toBe(true);
219
+ });
220
+
221
+ it('should return true for the same path', () => {
222
+ expect(isSubpath('/a/b', '/a/b')).toBe(true);
223
+ });
224
+
225
+ it('should return false for a parent path', () => {
226
+ expect(isSubpath('/a/b/c', '/a/b')).toBe(false);
227
+ });
228
+
229
+ it('should return false for a completely different path', () => {
230
+ expect(isSubpath('/a/b', '/x/y')).toBe(false);
231
+ });
232
+
233
+ it('should handle relative paths', () => {
234
+ expect(isSubpath('a/b', 'a/b/c')).toBe(true);
235
+ expect(isSubpath('a/b', 'a/c')).toBe(false);
236
+ });
237
+
238
+ it('should handle paths with ..', () => {
239
+ expect(isSubpath('/a/b', '/a/b/../b/c')).toBe(true);
240
+ expect(isSubpath('/a/b', '/a/c/../b')).toBe(true);
241
+ });
242
+
243
+ it('should handle root paths', () => {
244
+ expect(isSubpath('/', '/a')).toBe(true);
245
+ expect(isSubpath('/a', '/')).toBe(false);
246
+ });
247
+
248
+ it('should handle trailing slashes', () => {
249
+ expect(isSubpath('/a/b/', '/a/b/c')).toBe(true);
250
+ expect(isSubpath('/a/b', '/a/b/c/')).toBe(true);
251
+ expect(isSubpath('/a/b/', '/a/b/c/')).toBe(true);
252
+ });
253
+ });
254
+
255
+ describe('isSubpath on Windows', () => {
256
+ const originalPlatform = process.platform;
257
+
258
+ beforeAll(() => {
259
+ Object.defineProperty(process, 'platform', {
260
+ value: 'win32',
261
+ });
262
+ });
263
+
264
+ afterAll(() => {
265
+ Object.defineProperty(process, 'platform', {
266
+ value: originalPlatform,
267
+ });
268
+ });
269
+
270
+ it('should return true for a direct subpath on Windows', () => {
271
+ expect(isSubpath('C:\\Users\\Test', 'C:\\Users\\Test\\file.txt')).toBe(
272
+ true,
273
+ );
274
+ });
275
+
276
+ it('should return true for the same path on Windows', () => {
277
+ expect(isSubpath('C:\\Users\\Test', 'C:\\Users\\Test')).toBe(true);
278
+ });
279
+
280
+ it('should return false for a parent path on Windows', () => {
281
+ expect(isSubpath('C:\\Users\\Test\\file.txt', 'C:\\Users\\Test')).toBe(
282
+ false,
283
+ );
284
+ });
285
+
286
+ it('should return false for a different drive on Windows', () => {
287
+ expect(isSubpath('C:\\Users\\Test', 'D:\\Users\\Test')).toBe(false);
288
+ });
289
+
290
+ it('should be case-insensitive for drive letters on Windows', () => {
291
+ expect(isSubpath('c:\\Users\\Test', 'C:\\Users\\Test\\file.txt')).toBe(
292
+ true,
293
+ );
294
+ });
295
+
296
+ it('should be case-insensitive for path components on Windows', () => {
297
+ expect(isSubpath('C:\\Users\\Test', 'c:\\users\\test\\file.txt')).toBe(
298
+ true,
299
+ );
300
+ });
301
+
302
+ it('should handle mixed slashes on Windows', () => {
303
+ expect(isSubpath('C:/Users/Test', 'C:\\Users\\Test\\file.txt')).toBe(true);
304
+ });
305
+
306
+ it('should handle trailing slashes on Windows', () => {
307
+ expect(isSubpath('C:\\Users\\Test\\', 'C:\\Users\\Test\\file.txt')).toBe(
308
+ true,
309
+ );
310
+ });
311
+
312
+ it('should handle relative paths correctly on Windows', () => {
313
+ expect(isSubpath('Users\\Test', 'Users\\Test\\file.txt')).toBe(true);
314
+ expect(isSubpath('Users\\Test\\file.txt', 'Users\\Test')).toBe(false);
315
+ });
316
+ });
projects/ui/qwen-code/packages/core/src/utils/paths.ts ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import path from 'node:path';
8
+ import os from 'os';
9
+ import * as crypto from 'crypto';
10
+
11
+ export const QWEN_DIR = '.qwen';
12
+ export const GOOGLE_ACCOUNTS_FILENAME = 'google_accounts.json';
13
+ const TMP_DIR_NAME = 'tmp';
14
+ const COMMANDS_DIR_NAME = 'commands';
15
+
16
+ /**
17
+ * Special characters that need to be escaped in file paths for shell compatibility.
18
+ * Includes: spaces, parentheses, brackets, braces, semicolons, ampersands, pipes,
19
+ * asterisks, question marks, dollar signs, backticks, quotes, hash, and other shell metacharacters.
20
+ */
21
+ export const SHELL_SPECIAL_CHARS = /[ \t()[\]{};|*?$`'"#&<>!~]/;
22
+
23
+ /**
24
+ * Replaces the home directory with a tilde.
25
+ * @param path - The path to tildeify.
26
+ * @returns The tildeified path.
27
+ */
28
+ export function tildeifyPath(path: string): string {
29
+ const homeDir = os.homedir();
30
+ if (path.startsWith(homeDir)) {
31
+ return path.replace(homeDir, '~');
32
+ }
33
+ return path;
34
+ }
35
+
36
+ /**
37
+ * Shortens a path string if it exceeds maxLen, prioritizing the start and end segments.
38
+ * Example: /path/to/a/very/long/file.txt -> /path/.../long/file.txt
39
+ */
40
+ export function shortenPath(filePath: string, maxLen: number = 35): string {
41
+ if (filePath.length <= maxLen) {
42
+ return filePath;
43
+ }
44
+
45
+ const parsedPath = path.parse(filePath);
46
+ const root = parsedPath.root;
47
+ const separator = path.sep;
48
+
49
+ // Get segments of the path *after* the root
50
+ const relativePath = filePath.substring(root.length);
51
+ const segments = relativePath.split(separator).filter((s) => s !== ''); // Filter out empty segments
52
+
53
+ // Handle cases with no segments after root (e.g., "/", "C:\") or only one segment
54
+ if (segments.length <= 1) {
55
+ // Fall back to simple start/end truncation for very short paths or single segments
56
+ const keepLen = Math.floor((maxLen - 3) / 2);
57
+ // Ensure keepLen is not negative if maxLen is very small
58
+ if (keepLen <= 0) {
59
+ return filePath.substring(0, maxLen - 3) + '...';
60
+ }
61
+ const start = filePath.substring(0, keepLen);
62
+ const end = filePath.substring(filePath.length - keepLen);
63
+ return `${start}...${end}`;
64
+ }
65
+
66
+ const firstDir = segments[0];
67
+ const lastSegment = segments[segments.length - 1];
68
+ const startComponent = root + firstDir;
69
+
70
+ const endPartSegments: string[] = [];
71
+ // Base length: separator + "..." + lastDir
72
+ let currentLength = separator.length + lastSegment.length;
73
+
74
+ // Iterate backwards through segments (excluding the first one)
75
+ for (let i = segments.length - 2; i >= 0; i--) {
76
+ const segment = segments[i];
77
+ // Length needed if we add this segment: current + separator + segment
78
+ const lengthWithSegment = currentLength + separator.length + segment.length;
79
+
80
+ if (lengthWithSegment <= maxLen) {
81
+ endPartSegments.unshift(segment); // Add to the beginning of the end part
82
+ currentLength = lengthWithSegment;
83
+ } else {
84
+ break;
85
+ }
86
+ }
87
+
88
+ let result = endPartSegments.join(separator) + separator + lastSegment;
89
+
90
+ if (currentLength > maxLen) {
91
+ return result;
92
+ }
93
+
94
+ // Construct the final path
95
+ result = startComponent + separator + result;
96
+
97
+ // As a final check, if the result is somehow still too long
98
+ // truncate the result string from the beginning, prefixing with "...".
99
+ if (result.length > maxLen) {
100
+ return '...' + result.substring(result.length - maxLen - 3);
101
+ }
102
+
103
+ return result;
104
+ }
105
+
106
+ /**
107
+ * Calculates the relative path from a root directory to a target path.
108
+ * Ensures both paths are resolved before calculating.
109
+ * Returns '.' if the target path is the same as the root directory.
110
+ *
111
+ * @param targetPath The absolute or relative path to make relative.
112
+ * @param rootDirectory The absolute path of the directory to make the target path relative to.
113
+ * @returns The relative path from rootDirectory to targetPath.
114
+ */
115
+ export function makeRelative(
116
+ targetPath: string,
117
+ rootDirectory: string,
118
+ ): string {
119
+ const resolvedTargetPath = path.resolve(targetPath);
120
+ const resolvedRootDirectory = path.resolve(rootDirectory);
121
+
122
+ const relativePath = path.relative(resolvedRootDirectory, resolvedTargetPath);
123
+
124
+ // If the paths are the same, path.relative returns '', return '.' instead
125
+ return relativePath || '.';
126
+ }
127
+
128
+ /**
129
+ * Escapes special characters in a file path like macOS terminal does.
130
+ * Escapes: spaces, parentheses, brackets, braces, semicolons, ampersands, pipes,
131
+ * asterisks, question marks, dollar signs, backticks, quotes, hash, and other shell metacharacters.
132
+ */
133
+ export function escapePath(filePath: string): string {
134
+ let result = '';
135
+ for (let i = 0; i < filePath.length; i++) {
136
+ const char = filePath[i];
137
+
138
+ // Count consecutive backslashes before this character
139
+ let backslashCount = 0;
140
+ for (let j = i - 1; j >= 0 && filePath[j] === '\\'; j--) {
141
+ backslashCount++;
142
+ }
143
+
144
+ // Character is already escaped if there's an odd number of backslashes before it
145
+ const isAlreadyEscaped = backslashCount % 2 === 1;
146
+
147
+ // Only escape if not already escaped
148
+ if (!isAlreadyEscaped && SHELL_SPECIAL_CHARS.test(char)) {
149
+ result += '\\' + char;
150
+ } else {
151
+ result += char;
152
+ }
153
+ }
154
+ return result;
155
+ }
156
+
157
+ /**
158
+ * Unescapes special characters in a file path.
159
+ * Removes backslash escaping from shell metacharacters.
160
+ */
161
+ export function unescapePath(filePath: string): string {
162
+ return filePath.replace(
163
+ new RegExp(`\\\\([${SHELL_SPECIAL_CHARS.source.slice(1, -1)}])`, 'g'),
164
+ '$1',
165
+ );
166
+ }
167
+
168
+ /**
169
+ * Generates a unique hash for a project based on its root path.
170
+ * @param projectRoot The absolute path to the project's root directory.
171
+ * @returns A SHA256 hash of the project root path.
172
+ */
173
+ export function getProjectHash(projectRoot: string): string {
174
+ return crypto.createHash('sha256').update(projectRoot).digest('hex');
175
+ }
176
+
177
+ /**
178
+ * Generates a unique temporary directory path for a project.
179
+ * @param projectRoot The absolute path to the project's root directory.
180
+ * @returns The path to the project's temporary directory.
181
+ */
182
+ export function getProjectTempDir(projectRoot: string): string {
183
+ const hash = getProjectHash(projectRoot);
184
+ return path.join(os.homedir(), QWEN_DIR, TMP_DIR_NAME, hash);
185
+ }
186
+
187
+ /**
188
+ * Returns the absolute path to the user-level commands directory.
189
+ * @returns The path to the user's commands directory.
190
+ */
191
+ export function getUserCommandsDir(): string {
192
+ return path.join(os.homedir(), QWEN_DIR, COMMANDS_DIR_NAME);
193
+ }
194
+
195
+ /**
196
+ * Returns the absolute path to the project-level commands directory.
197
+ * @param projectRoot The absolute path to the project's root directory.
198
+ * @returns The path to the project's commands directory.
199
+ */
200
+ export function getProjectCommandsDir(projectRoot: string): string {
201
+ return path.join(projectRoot, QWEN_DIR, COMMANDS_DIR_NAME);
202
+ }
203
+
204
+ /**
205
+ * Checks if a path is a subpath of another path.
206
+ * @param parentPath The parent path.
207
+ * @param childPath The child path.
208
+ * @returns True if childPath is a subpath of parentPath, false otherwise.
209
+ */
210
+ export function isSubpath(parentPath: string, childPath: string): boolean {
211
+ const isWindows = os.platform() === 'win32';
212
+ const pathModule = isWindows ? path.win32 : path;
213
+
214
+ // On Windows, path.relative is case-insensitive. On POSIX, it's case-sensitive.
215
+ const relative = pathModule.relative(parentPath, childPath);
216
+
217
+ return (
218
+ !relative.startsWith(`..${pathModule.sep}`) &&
219
+ relative !== '..' &&
220
+ !pathModule.isAbsolute(relative)
221
+ );
222
+ }
projects/ui/qwen-code/packages/core/src/utils/quotaErrorDetection.test.ts ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ isQwenQuotaExceededError,
10
+ isQwenThrottlingError,
11
+ isProQuotaExceededError,
12
+ isGenericQuotaExceededError,
13
+ isApiError,
14
+ isStructuredError,
15
+ type ApiError,
16
+ } from './quotaErrorDetection.js';
17
+
18
+ describe('quotaErrorDetection', () => {
19
+ describe('isQwenQuotaExceededError', () => {
20
+ it('should detect insufficient_quota error message', () => {
21
+ const error = new Error('insufficient_quota');
22
+ expect(isQwenQuotaExceededError(error)).toBe(true);
23
+ });
24
+
25
+ it('should detect free allocated quota exceeded error message', () => {
26
+ const error = new Error('Free allocated quota exceeded.');
27
+ expect(isQwenQuotaExceededError(error)).toBe(true);
28
+ });
29
+
30
+ it('should detect quota exceeded error message', () => {
31
+ const error = new Error('quota exceeded');
32
+ expect(isQwenQuotaExceededError(error)).toBe(true);
33
+ });
34
+
35
+ it('should detect quota exceeded in string error', () => {
36
+ const error = 'insufficient_quota';
37
+ expect(isQwenQuotaExceededError(error)).toBe(true);
38
+ });
39
+
40
+ it('should detect quota exceeded in structured error', () => {
41
+ const error = { message: 'Free allocated quota exceeded.', status: 429 };
42
+ expect(isQwenQuotaExceededError(error)).toBe(true);
43
+ });
44
+
45
+ it('should detect quota exceeded in API error', () => {
46
+ const error: ApiError = {
47
+ error: {
48
+ code: 429,
49
+ message: 'insufficient_quota',
50
+ status: 'RESOURCE_EXHAUSTED',
51
+ details: [],
52
+ },
53
+ };
54
+ expect(isQwenQuotaExceededError(error)).toBe(true);
55
+ });
56
+
57
+ it('should not detect throttling errors as quota exceeded', () => {
58
+ const error = new Error('requests throttling triggered');
59
+ expect(isQwenQuotaExceededError(error)).toBe(false);
60
+ });
61
+
62
+ it('should not detect unrelated errors', () => {
63
+ const error = new Error('Network error');
64
+ expect(isQwenQuotaExceededError(error)).toBe(false);
65
+ });
66
+ });
67
+
68
+ describe('isQwenThrottlingError', () => {
69
+ it('should detect throttling error with 429 status', () => {
70
+ const error = { message: 'throttling', status: 429 };
71
+ expect(isQwenThrottlingError(error)).toBe(true);
72
+ });
73
+
74
+ it('should detect requests throttling triggered with 429 status', () => {
75
+ const error = { message: 'requests throttling triggered', status: 429 };
76
+ expect(isQwenThrottlingError(error)).toBe(true);
77
+ });
78
+
79
+ it('should detect rate limit error with 429 status', () => {
80
+ const error = { message: 'rate limit exceeded', status: 429 };
81
+ expect(isQwenThrottlingError(error)).toBe(true);
82
+ });
83
+
84
+ it('should detect too many requests with 429 status', () => {
85
+ const error = { message: 'too many requests', status: 429 };
86
+ expect(isQwenThrottlingError(error)).toBe(true);
87
+ });
88
+
89
+ it('should detect throttling in string error', () => {
90
+ const error = 'throttling';
91
+ expect(isQwenThrottlingError(error)).toBe(true);
92
+ });
93
+
94
+ it('should detect throttling in structured error with 429', () => {
95
+ const error = { message: 'requests throttling triggered', status: 429 };
96
+ expect(isQwenThrottlingError(error)).toBe(true);
97
+ });
98
+
99
+ it('should detect throttling in API error with 429', () => {
100
+ const error: ApiError = {
101
+ error: {
102
+ code: 429,
103
+ message: 'throttling',
104
+ status: 'RESOURCE_EXHAUSTED',
105
+ details: [],
106
+ },
107
+ };
108
+ expect(isQwenThrottlingError(error)).toBe(true);
109
+ });
110
+
111
+ it('should not detect throttling without 429 status in structured error', () => {
112
+ const error = { message: 'throttling', status: 500 };
113
+ expect(isQwenThrottlingError(error)).toBe(false);
114
+ });
115
+
116
+ it('should not detect quota exceeded as throttling', () => {
117
+ const error = { message: 'insufficient_quota', status: 429 };
118
+ expect(isQwenThrottlingError(error)).toBe(false);
119
+ });
120
+
121
+ it('should not detect unrelated errors as throttling', () => {
122
+ const error = { message: 'Network error', status: 500 };
123
+ expect(isQwenThrottlingError(error)).toBe(false);
124
+ });
125
+ });
126
+
127
+ describe('isProQuotaExceededError', () => {
128
+ it('should detect Gemini Pro quota exceeded error', () => {
129
+ const error = new Error(
130
+ "Quota exceeded for quota metric 'Gemini 2.5 Pro Requests'",
131
+ );
132
+ expect(isProQuotaExceededError(error)).toBe(true);
133
+ });
134
+
135
+ it('should detect Gemini preview Pro quota exceeded error', () => {
136
+ const error = new Error(
137
+ "Quota exceeded for quota metric 'Gemini 2.5-preview Pro Requests'",
138
+ );
139
+ expect(isProQuotaExceededError(error)).toBe(true);
140
+ });
141
+
142
+ it('should not detect non-Pro quota errors', () => {
143
+ const error = new Error(
144
+ "Quota exceeded for quota metric 'Gemini 1.5 Flash Requests'",
145
+ );
146
+ expect(isProQuotaExceededError(error)).toBe(false);
147
+ });
148
+ });
149
+
150
+ describe('isGenericQuotaExceededError', () => {
151
+ it('should detect generic quota exceeded error', () => {
152
+ const error = new Error('Quota exceeded for quota metric');
153
+ expect(isGenericQuotaExceededError(error)).toBe(true);
154
+ });
155
+
156
+ it('should not detect non-quota errors', () => {
157
+ const error = new Error('Network error');
158
+ expect(isGenericQuotaExceededError(error)).toBe(false);
159
+ });
160
+ });
161
+
162
+ describe('type guards', () => {
163
+ describe('isApiError', () => {
164
+ it('should detect valid API error', () => {
165
+ const error: ApiError = {
166
+ error: {
167
+ code: 429,
168
+ message: 'test error',
169
+ status: 'RESOURCE_EXHAUSTED',
170
+ details: [],
171
+ },
172
+ };
173
+ expect(isApiError(error)).toBe(true);
174
+ });
175
+
176
+ it('should not detect invalid API error', () => {
177
+ const error = { message: 'test error' };
178
+ expect(isApiError(error)).toBe(false);
179
+ });
180
+ });
181
+
182
+ describe('isStructuredError', () => {
183
+ it('should detect valid structured error', () => {
184
+ const error = { message: 'test error', status: 429 };
185
+ expect(isStructuredError(error)).toBe(true);
186
+ });
187
+
188
+ it('should not detect invalid structured error', () => {
189
+ const error = { code: 429 };
190
+ expect(isStructuredError(error)).toBe(false);
191
+ });
192
+ });
193
+ });
194
+ });
projects/ui/qwen-code/packages/core/src/utils/quotaErrorDetection.ts ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { StructuredError } from '../core/turn.js';
8
+
9
+ export interface ApiError {
10
+ error: {
11
+ code: number;
12
+ message: string;
13
+ status: string;
14
+ details: unknown[];
15
+ };
16
+ }
17
+
18
+ export function isApiError(error: unknown): error is ApiError {
19
+ return (
20
+ typeof error === 'object' &&
21
+ error !== null &&
22
+ 'error' in error &&
23
+ typeof (error as ApiError).error === 'object' &&
24
+ 'message' in (error as ApiError).error
25
+ );
26
+ }
27
+
28
+ export function isStructuredError(error: unknown): error is StructuredError {
29
+ return (
30
+ typeof error === 'object' &&
31
+ error !== null &&
32
+ 'message' in error &&
33
+ typeof (error as StructuredError).message === 'string'
34
+ );
35
+ }
36
+
37
+ export function isProQuotaExceededError(error: unknown): boolean {
38
+ // Check for Pro quota exceeded errors by looking for the specific pattern
39
+ // This will match patterns like:
40
+ // - "Quota exceeded for quota metric 'Gemini 2.5 Pro Requests'"
41
+ // - "Quota exceeded for quota metric 'Gemini 2.5-preview Pro Requests'"
42
+ // We use string methods instead of regex to avoid ReDoS vulnerabilities
43
+
44
+ const checkMessage = (message: string): boolean =>
45
+ message.includes("Quota exceeded for quota metric 'Gemini") &&
46
+ message.includes("Pro Requests'");
47
+
48
+ if (typeof error === 'string') {
49
+ return checkMessage(error);
50
+ }
51
+
52
+ if (isStructuredError(error)) {
53
+ return checkMessage(error.message);
54
+ }
55
+
56
+ if (isApiError(error)) {
57
+ return checkMessage(error.error.message);
58
+ }
59
+
60
+ // Check if it's a Gaxios error with response data
61
+ if (error && typeof error === 'object' && 'response' in error) {
62
+ const gaxiosError = error as {
63
+ response?: {
64
+ data?: unknown;
65
+ };
66
+ };
67
+ if (gaxiosError.response && gaxiosError.response.data) {
68
+ if (typeof gaxiosError.response.data === 'string') {
69
+ return checkMessage(gaxiosError.response.data);
70
+ }
71
+ if (
72
+ typeof gaxiosError.response.data === 'object' &&
73
+ gaxiosError.response.data !== null &&
74
+ 'error' in gaxiosError.response.data
75
+ ) {
76
+ const errorData = gaxiosError.response.data as {
77
+ error?: { message?: string };
78
+ };
79
+ return checkMessage(errorData.error?.message || '');
80
+ }
81
+ }
82
+ }
83
+ return false;
84
+ }
85
+
86
+ export function isGenericQuotaExceededError(error: unknown): boolean {
87
+ if (typeof error === 'string') {
88
+ return error.includes('Quota exceeded for quota metric');
89
+ }
90
+
91
+ if (isStructuredError(error)) {
92
+ return error.message.includes('Quota exceeded for quota metric');
93
+ }
94
+
95
+ if (isApiError(error)) {
96
+ return error.error.message.includes('Quota exceeded for quota metric');
97
+ }
98
+
99
+ return false;
100
+ }
101
+
102
+ export function isQwenQuotaExceededError(error: unknown): boolean {
103
+ // Check for Qwen insufficient quota errors (should not retry)
104
+ const checkMessage = (message: string): boolean => {
105
+ const lowerMessage = message.toLowerCase();
106
+ return (
107
+ lowerMessage.includes('insufficient_quota') ||
108
+ lowerMessage.includes('free allocated quota exceeded') ||
109
+ (lowerMessage.includes('quota') && lowerMessage.includes('exceeded'))
110
+ );
111
+ };
112
+
113
+ if (typeof error === 'string') {
114
+ return checkMessage(error);
115
+ }
116
+
117
+ if (isStructuredError(error)) {
118
+ return checkMessage(error.message);
119
+ }
120
+
121
+ if (isApiError(error)) {
122
+ return checkMessage(error.error.message);
123
+ }
124
+
125
+ return false;
126
+ }
127
+
128
+ export function isQwenThrottlingError(error: unknown): boolean {
129
+ // Check for Qwen throttling errors (should retry)
130
+ const checkMessage = (message: string): boolean => {
131
+ const lowerMessage = message.toLowerCase();
132
+ return (
133
+ lowerMessage.includes('throttling') ||
134
+ lowerMessage.includes('requests throttling triggered') ||
135
+ lowerMessage.includes('rate limit') ||
136
+ lowerMessage.includes('too many requests')
137
+ );
138
+ };
139
+
140
+ // Check status code
141
+ const getStatusCode = (error: unknown): number | undefined => {
142
+ if (error && typeof error === 'object') {
143
+ const errorObj = error as { status?: number; code?: number };
144
+ return errorObj.status || errorObj.code;
145
+ }
146
+ return undefined;
147
+ };
148
+
149
+ const statusCode = getStatusCode(error);
150
+
151
+ if (typeof error === 'string') {
152
+ return (
153
+ (statusCode === 429 && checkMessage(error)) ||
154
+ error.includes('throttling')
155
+ );
156
+ }
157
+
158
+ if (isStructuredError(error)) {
159
+ return statusCode === 429 && checkMessage(error.message);
160
+ }
161
+
162
+ if (isApiError(error)) {
163
+ return error.error.code === 429 && checkMessage(error.error.message);
164
+ }
165
+
166
+ return false;
167
+ }
projects/ui/qwen-code/packages/core/src/utils/retry.test.ts ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /* eslint-disable @typescript-eslint/no-explicit-any */
8
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
9
+ import { retryWithBackoff, HttpError } from './retry.js';
10
+ import { setSimulate429 } from './testUtils.js';
11
+ import { AuthType } from '../core/contentGenerator.js';
12
+
13
+ // Helper to create a mock function that fails a certain number of times
14
+ const createFailingFunction = (
15
+ failures: number,
16
+ successValue: string = 'success',
17
+ ) => {
18
+ let attempts = 0;
19
+ return vi.fn(async () => {
20
+ attempts++;
21
+ if (attempts <= failures) {
22
+ // Simulate a retryable error
23
+ const error: HttpError = new Error(`Simulated error attempt ${attempts}`);
24
+ error.status = 500; // Simulate a server error
25
+ throw error;
26
+ }
27
+ return successValue;
28
+ });
29
+ };
30
+
31
+ // Custom error for testing non-retryable conditions
32
+ class NonRetryableError extends Error {
33
+ constructor(message: string) {
34
+ super(message);
35
+ this.name = 'NonRetryableError';
36
+ }
37
+ }
38
+
39
+ describe('retryWithBackoff', () => {
40
+ beforeEach(() => {
41
+ vi.useFakeTimers();
42
+ // Disable 429 simulation for tests
43
+ setSimulate429(false);
44
+ // Suppress unhandled promise rejection warnings for tests that expect errors
45
+ console.warn = vi.fn();
46
+ });
47
+
48
+ afterEach(() => {
49
+ vi.restoreAllMocks();
50
+ vi.useRealTimers();
51
+ });
52
+
53
+ it('should return the result on the first attempt if successful', async () => {
54
+ const mockFn = createFailingFunction(0);
55
+ const result = await retryWithBackoff(mockFn);
56
+ expect(result).toBe('success');
57
+ expect(mockFn).toHaveBeenCalledTimes(1);
58
+ });
59
+
60
+ it('should retry and succeed if failures are within maxAttempts', async () => {
61
+ const mockFn = createFailingFunction(2);
62
+ const promise = retryWithBackoff(mockFn, {
63
+ maxAttempts: 3,
64
+ initialDelayMs: 10,
65
+ });
66
+
67
+ await vi.runAllTimersAsync(); // Ensure all delays and retries complete
68
+
69
+ const result = await promise;
70
+ expect(result).toBe('success');
71
+ expect(mockFn).toHaveBeenCalledTimes(3);
72
+ });
73
+
74
+ it('should throw an error if all attempts fail', async () => {
75
+ const mockFn = createFailingFunction(3);
76
+
77
+ // 1. Start the retryable operation, which returns a promise.
78
+ const promise = retryWithBackoff(mockFn, {
79
+ maxAttempts: 3,
80
+ initialDelayMs: 10,
81
+ });
82
+
83
+ // 2. IMPORTANT: Attach the rejection expectation to the promise *immediately*.
84
+ // This ensures a 'catch' handler is present before the promise can reject.
85
+ // The result is a new promise that resolves when the assertion is met.
86
+ const assertionPromise = expect(promise).rejects.toThrow(
87
+ 'Simulated error attempt 3',
88
+ );
89
+
90
+ // 3. Now, advance the timers. This will trigger the retries and the
91
+ // eventual rejection. The handler attached in step 2 will catch it.
92
+ await vi.runAllTimersAsync();
93
+
94
+ // 4. Await the assertion promise itself to ensure the test was successful.
95
+ await assertionPromise;
96
+
97
+ // 5. Finally, assert the number of calls.
98
+ expect(mockFn).toHaveBeenCalledTimes(3);
99
+ });
100
+
101
+ it('should not retry if shouldRetry returns false', async () => {
102
+ const mockFn = vi.fn(async () => {
103
+ throw new NonRetryableError('Non-retryable error');
104
+ });
105
+ const shouldRetry = (error: Error) => !(error instanceof NonRetryableError);
106
+
107
+ const promise = retryWithBackoff(mockFn, {
108
+ shouldRetry,
109
+ initialDelayMs: 10,
110
+ });
111
+
112
+ await expect(promise).rejects.toThrow('Non-retryable error');
113
+ expect(mockFn).toHaveBeenCalledTimes(1);
114
+ });
115
+
116
+ it('should use default shouldRetry if not provided, retrying on 429', async () => {
117
+ const mockFn = vi.fn(async () => {
118
+ const error = new Error('Too Many Requests') as any;
119
+ error.status = 429;
120
+ throw error;
121
+ });
122
+
123
+ const promise = retryWithBackoff(mockFn, {
124
+ maxAttempts: 2,
125
+ initialDelayMs: 10,
126
+ });
127
+
128
+ // Attach the rejection expectation *before* running timers
129
+ const assertionPromise =
130
+ expect(promise).rejects.toThrow('Too Many Requests');
131
+
132
+ // Run timers to trigger retries and eventual rejection
133
+ await vi.runAllTimersAsync();
134
+
135
+ // Await the assertion
136
+ await assertionPromise;
137
+
138
+ expect(mockFn).toHaveBeenCalledTimes(2);
139
+ });
140
+
141
+ it('should use default shouldRetry if not provided, not retrying on 400', async () => {
142
+ const mockFn = vi.fn(async () => {
143
+ const error = new Error('Bad Request') as any;
144
+ error.status = 400;
145
+ throw error;
146
+ });
147
+
148
+ const promise = retryWithBackoff(mockFn, {
149
+ maxAttempts: 2,
150
+ initialDelayMs: 10,
151
+ });
152
+ await expect(promise).rejects.toThrow('Bad Request');
153
+ expect(mockFn).toHaveBeenCalledTimes(1);
154
+ });
155
+
156
+ it('should respect maxDelayMs', async () => {
157
+ const mockFn = createFailingFunction(3);
158
+ const setTimeoutSpy = vi.spyOn(global, 'setTimeout');
159
+
160
+ const promise = retryWithBackoff(mockFn, {
161
+ maxAttempts: 4,
162
+ initialDelayMs: 100,
163
+ maxDelayMs: 250, // Max delay is less than 100 * 2 * 2 = 400
164
+ });
165
+
166
+ await vi.advanceTimersByTimeAsync(1000); // Advance well past all delays
167
+ await promise;
168
+
169
+ const delays = setTimeoutSpy.mock.calls.map((call) => call[1] as number);
170
+
171
+ // Delays should be around initial, initial*2, maxDelay (due to cap)
172
+ // Jitter makes exact assertion hard, so we check ranges / caps
173
+ expect(delays.length).toBe(3);
174
+ expect(delays[0]).toBeGreaterThanOrEqual(100 * 0.7);
175
+ expect(delays[0]).toBeLessThanOrEqual(100 * 1.3);
176
+ expect(delays[1]).toBeGreaterThanOrEqual(200 * 0.7);
177
+ expect(delays[1]).toBeLessThanOrEqual(200 * 1.3);
178
+ // The third delay should be capped by maxDelayMs (250ms), accounting for jitter
179
+ expect(delays[2]).toBeGreaterThanOrEqual(250 * 0.7);
180
+ expect(delays[2]).toBeLessThanOrEqual(250 * 1.3);
181
+ });
182
+
183
+ it('should handle jitter correctly, ensuring varied delays', async () => {
184
+ let mockFn = createFailingFunction(5);
185
+ const setTimeoutSpy = vi.spyOn(global, 'setTimeout');
186
+
187
+ // Run retryWithBackoff multiple times to observe jitter
188
+ const runRetry = () =>
189
+ retryWithBackoff(mockFn, {
190
+ maxAttempts: 2, // Only one retry, so one delay
191
+ initialDelayMs: 100,
192
+ maxDelayMs: 1000,
193
+ });
194
+
195
+ // We expect rejections as mockFn fails 5 times
196
+ const promise1 = runRetry();
197
+ // Attach the rejection expectation *before* running timers
198
+ const assertionPromise1 = expect(promise1).rejects.toThrow();
199
+ await vi.runAllTimersAsync(); // Advance for the delay in the first runRetry
200
+ await assertionPromise1;
201
+
202
+ const firstDelaySet = setTimeoutSpy.mock.calls.map(
203
+ (call) => call[1] as number,
204
+ );
205
+ setTimeoutSpy.mockClear(); // Clear calls for the next run
206
+
207
+ // Reset mockFn to reset its internal attempt counter for the next run
208
+ mockFn = createFailingFunction(5); // Re-initialize with 5 failures
209
+
210
+ const promise2 = runRetry();
211
+ // Attach the rejection expectation *before* running timers
212
+ const assertionPromise2 = expect(promise2).rejects.toThrow();
213
+ await vi.runAllTimersAsync(); // Advance for the delay in the second runRetry
214
+ await assertionPromise2;
215
+
216
+ const secondDelaySet = setTimeoutSpy.mock.calls.map(
217
+ (call) => call[1] as number,
218
+ );
219
+
220
+ // Check that the delays are not exactly the same due to jitter
221
+ // This is a probabilistic test, but with +/-30% jitter, it's highly likely they differ.
222
+ if (firstDelaySet.length > 0 && secondDelaySet.length > 0) {
223
+ // Check the first delay of each set
224
+ expect(firstDelaySet[0]).not.toBe(secondDelaySet[0]);
225
+ } else {
226
+ // If somehow no delays were captured (e.g. test setup issue), fail explicitly
227
+ throw new Error('Delays were not captured for jitter test');
228
+ }
229
+
230
+ // Ensure delays are within the expected jitter range [70, 130] for initialDelayMs = 100
231
+ [...firstDelaySet, ...secondDelaySet].forEach((d) => {
232
+ expect(d).toBeGreaterThanOrEqual(100 * 0.7);
233
+ expect(d).toBeLessThanOrEqual(100 * 1.3);
234
+ });
235
+ });
236
+
237
+ describe('Flash model fallback for OAuth users', () => {
238
+ it('should trigger fallback for OAuth personal users after persistent 429 errors', async () => {
239
+ const fallbackCallback = vi.fn().mockResolvedValue('gemini-2.5-flash');
240
+
241
+ let fallbackOccurred = false;
242
+ const mockFn = vi.fn().mockImplementation(async () => {
243
+ if (!fallbackOccurred) {
244
+ const error: HttpError = new Error('Rate limit exceeded');
245
+ error.status = 429;
246
+ throw error;
247
+ }
248
+ return 'success';
249
+ });
250
+
251
+ const promise = retryWithBackoff(mockFn, {
252
+ maxAttempts: 3,
253
+ initialDelayMs: 100,
254
+ onPersistent429: async (authType?: string) => {
255
+ fallbackOccurred = true;
256
+ return await fallbackCallback(authType);
257
+ },
258
+ authType: 'oauth-personal',
259
+ });
260
+
261
+ // Advance all timers to complete retries
262
+ await vi.runAllTimersAsync();
263
+
264
+ // Should succeed after fallback
265
+ await expect(promise).resolves.toBe('success');
266
+
267
+ // Verify callback was called with correct auth type
268
+ expect(fallbackCallback).toHaveBeenCalledWith('oauth-personal');
269
+
270
+ // Should retry again after fallback
271
+ expect(mockFn).toHaveBeenCalledTimes(3); // 2 initial attempts + 1 after fallback
272
+ });
273
+
274
+ it('should NOT trigger fallback for API key users', async () => {
275
+ const fallbackCallback = vi.fn();
276
+
277
+ const mockFn = vi.fn(async () => {
278
+ const error: HttpError = new Error('Rate limit exceeded');
279
+ error.status = 429;
280
+ throw error;
281
+ });
282
+
283
+ const promise = retryWithBackoff(mockFn, {
284
+ maxAttempts: 3,
285
+ initialDelayMs: 100,
286
+ onPersistent429: fallbackCallback,
287
+ authType: 'gemini-api-key',
288
+ });
289
+
290
+ // Handle the promise properly to avoid unhandled rejections
291
+ const resultPromise = promise.catch((error) => error);
292
+ await vi.runAllTimersAsync();
293
+ const result = await resultPromise;
294
+
295
+ // Should fail after all retries without fallback
296
+ expect(result).toBeInstanceOf(Error);
297
+ expect(result.message).toBe('Rate limit exceeded');
298
+
299
+ // Callback should not be called for API key users
300
+ expect(fallbackCallback).not.toHaveBeenCalled();
301
+ });
302
+
303
+ it('should reset attempt counter and continue after successful fallback', async () => {
304
+ let fallbackCalled = false;
305
+ const fallbackCallback = vi.fn().mockImplementation(async () => {
306
+ fallbackCalled = true;
307
+ return 'gemini-2.5-flash';
308
+ });
309
+
310
+ const mockFn = vi.fn().mockImplementation(async () => {
311
+ if (!fallbackCalled) {
312
+ const error: HttpError = new Error('Rate limit exceeded');
313
+ error.status = 429;
314
+ throw error;
315
+ }
316
+ return 'success';
317
+ });
318
+
319
+ const promise = retryWithBackoff(mockFn, {
320
+ maxAttempts: 3,
321
+ initialDelayMs: 100,
322
+ onPersistent429: fallbackCallback,
323
+ authType: 'oauth-personal',
324
+ });
325
+
326
+ await vi.runAllTimersAsync();
327
+
328
+ await expect(promise).resolves.toBe('success');
329
+ expect(fallbackCallback).toHaveBeenCalledOnce();
330
+ });
331
+
332
+ it('should continue with original error if fallback is rejected', async () => {
333
+ const fallbackCallback = vi.fn().mockResolvedValue(null); // User rejected fallback
334
+
335
+ const mockFn = vi.fn(async () => {
336
+ const error: HttpError = new Error('Rate limit exceeded');
337
+ error.status = 429;
338
+ throw error;
339
+ });
340
+
341
+ const promise = retryWithBackoff(mockFn, {
342
+ maxAttempts: 3,
343
+ initialDelayMs: 100,
344
+ onPersistent429: fallbackCallback,
345
+ authType: 'oauth-personal',
346
+ });
347
+
348
+ // Handle the promise properly to avoid unhandled rejections
349
+ const resultPromise = promise.catch((error) => error);
350
+ await vi.runAllTimersAsync();
351
+ const result = await resultPromise;
352
+
353
+ // Should fail with original error when fallback is rejected
354
+ expect(result).toBeInstanceOf(Error);
355
+ expect(result.message).toBe('Rate limit exceeded');
356
+ expect(fallbackCallback).toHaveBeenCalledWith(
357
+ 'oauth-personal',
358
+ expect.any(Error),
359
+ );
360
+ });
361
+
362
+ it('should handle mixed error types (only count consecutive 429s)', async () => {
363
+ const fallbackCallback = vi.fn().mockResolvedValue('gemini-2.5-flash');
364
+ let attempts = 0;
365
+ let fallbackOccurred = false;
366
+
367
+ const mockFn = vi.fn().mockImplementation(async () => {
368
+ attempts++;
369
+ if (fallbackOccurred) {
370
+ return 'success';
371
+ }
372
+ if (attempts === 1) {
373
+ // First attempt: 500 error (resets consecutive count)
374
+ const error: HttpError = new Error('Server error');
375
+ error.status = 500;
376
+ throw error;
377
+ } else {
378
+ // Remaining attempts: 429 errors
379
+ const error: HttpError = new Error('Rate limit exceeded');
380
+ error.status = 429;
381
+ throw error;
382
+ }
383
+ });
384
+
385
+ const promise = retryWithBackoff(mockFn, {
386
+ maxAttempts: 5,
387
+ initialDelayMs: 100,
388
+ onPersistent429: async (authType?: string) => {
389
+ fallbackOccurred = true;
390
+ return await fallbackCallback(authType);
391
+ },
392
+ authType: 'oauth-personal',
393
+ });
394
+
395
+ await vi.runAllTimersAsync();
396
+
397
+ await expect(promise).resolves.toBe('success');
398
+
399
+ // Should trigger fallback after 2 consecutive 429s (attempts 2-3)
400
+ expect(fallbackCallback).toHaveBeenCalledWith('oauth-personal');
401
+ });
402
+ });
403
+
404
+ describe('Qwen OAuth 429 error handling', () => {
405
+ it('should retry for Qwen OAuth 429 errors that are throttling-related', async () => {
406
+ const errorWith429: HttpError = new Error('Rate limit exceeded');
407
+ errorWith429.status = 429;
408
+
409
+ const fn = vi
410
+ .fn()
411
+ .mockRejectedValueOnce(errorWith429)
412
+ .mockResolvedValue('success');
413
+
414
+ const promise = retryWithBackoff(fn, {
415
+ maxAttempts: 5,
416
+ initialDelayMs: 100,
417
+ maxDelayMs: 1000,
418
+ shouldRetry: () => true,
419
+ authType: AuthType.QWEN_OAUTH,
420
+ });
421
+
422
+ // Fast-forward time for delays
423
+ await vi.runAllTimersAsync();
424
+
425
+ await expect(promise).resolves.toBe('success');
426
+
427
+ // Should be called twice (1 failure + 1 success)
428
+ expect(fn).toHaveBeenCalledTimes(2);
429
+ });
430
+
431
+ it('should throw immediately for Qwen OAuth with insufficient_quota message', async () => {
432
+ const errorWithInsufficientQuota = new Error('insufficient_quota');
433
+
434
+ const fn = vi.fn().mockRejectedValue(errorWithInsufficientQuota);
435
+
436
+ const promise = retryWithBackoff(fn, {
437
+ maxAttempts: 5,
438
+ initialDelayMs: 1000,
439
+ maxDelayMs: 5000,
440
+ shouldRetry: () => true,
441
+ authType: AuthType.QWEN_OAUTH,
442
+ });
443
+
444
+ await expect(promise).rejects.toThrow(/Qwen API quota exceeded/);
445
+
446
+ // Should be called only once (no retries)
447
+ expect(fn).toHaveBeenCalledTimes(1);
448
+ });
449
+
450
+ it('should throw immediately for Qwen OAuth with free allocated quota exceeded message', async () => {
451
+ const errorWithQuotaExceeded = new Error(
452
+ 'Free allocated quota exceeded.',
453
+ );
454
+
455
+ const fn = vi.fn().mockRejectedValue(errorWithQuotaExceeded);
456
+
457
+ const promise = retryWithBackoff(fn, {
458
+ maxAttempts: 5,
459
+ initialDelayMs: 1000,
460
+ maxDelayMs: 5000,
461
+ shouldRetry: () => true,
462
+ authType: AuthType.QWEN_OAUTH,
463
+ });
464
+
465
+ await expect(promise).rejects.toThrow(/Qwen API quota exceeded/);
466
+
467
+ // Should be called only once (no retries)
468
+ expect(fn).toHaveBeenCalledTimes(1);
469
+ });
470
+
471
+ it('should retry for Qwen OAuth with throttling message', async () => {
472
+ const throttlingError: HttpError = new Error(
473
+ 'requests throttling triggered',
474
+ );
475
+ throttlingError.status = 429;
476
+
477
+ const fn = vi
478
+ .fn()
479
+ .mockRejectedValueOnce(throttlingError)
480
+ .mockRejectedValueOnce(throttlingError)
481
+ .mockResolvedValue('success');
482
+
483
+ const promise = retryWithBackoff(fn, {
484
+ maxAttempts: 5,
485
+ initialDelayMs: 100,
486
+ maxDelayMs: 1000,
487
+ shouldRetry: () => true,
488
+ authType: AuthType.QWEN_OAUTH,
489
+ });
490
+
491
+ // Fast-forward time for delays
492
+ await vi.runAllTimersAsync();
493
+
494
+ await expect(promise).resolves.toBe('success');
495
+
496
+ // Should be called 3 times (2 failures + 1 success)
497
+ expect(fn).toHaveBeenCalledTimes(3);
498
+ });
499
+
500
+ it('should retry for Qwen OAuth with throttling error', async () => {
501
+ const throttlingError: HttpError = new Error('throttling');
502
+ throttlingError.status = 429;
503
+
504
+ const fn = vi
505
+ .fn()
506
+ .mockRejectedValueOnce(throttlingError)
507
+ .mockResolvedValue('success');
508
+
509
+ const promise = retryWithBackoff(fn, {
510
+ maxAttempts: 5,
511
+ initialDelayMs: 100,
512
+ maxDelayMs: 1000,
513
+ shouldRetry: () => true,
514
+ authType: AuthType.QWEN_OAUTH,
515
+ });
516
+
517
+ // Fast-forward time for delays
518
+ await vi.runAllTimersAsync();
519
+
520
+ await expect(promise).resolves.toBe('success');
521
+
522
+ // Should be called 2 times (1 failure + 1 success)
523
+ expect(fn).toHaveBeenCalledTimes(2);
524
+ });
525
+
526
+ it('should throw immediately for Qwen OAuth with quota message', async () => {
527
+ const errorWithQuota = new Error('quota exceeded');
528
+
529
+ const fn = vi.fn().mockRejectedValue(errorWithQuota);
530
+
531
+ const promise = retryWithBackoff(fn, {
532
+ maxAttempts: 5,
533
+ initialDelayMs: 1000,
534
+ maxDelayMs: 5000,
535
+ shouldRetry: () => true,
536
+ authType: AuthType.QWEN_OAUTH,
537
+ });
538
+
539
+ await expect(promise).rejects.toThrow(/Qwen API quota exceeded/);
540
+
541
+ // Should be called only once (no retries)
542
+ expect(fn).toHaveBeenCalledTimes(1);
543
+ });
544
+
545
+ it('should retry normal errors for Qwen OAuth (not quota-related)', async () => {
546
+ const normalError: HttpError = new Error('Network error');
547
+ normalError.status = 500;
548
+
549
+ const fn = createFailingFunction(2, 'success');
550
+ // Replace the default 500 error with our normal error
551
+ fn.mockRejectedValueOnce(normalError)
552
+ .mockRejectedValueOnce(normalError)
553
+ .mockResolvedValue('success');
554
+
555
+ const promise = retryWithBackoff(fn, {
556
+ maxAttempts: 5,
557
+ initialDelayMs: 100,
558
+ maxDelayMs: 1000,
559
+ shouldRetry: () => true,
560
+ authType: AuthType.QWEN_OAUTH,
561
+ });
562
+
563
+ // Fast-forward time for delays
564
+ await vi.runAllTimersAsync();
565
+
566
+ await expect(promise).resolves.toBe('success');
567
+
568
+ // Should be called 3 times (2 failures + 1 success)
569
+ expect(fn).toHaveBeenCalledTimes(3);
570
+ });
571
+ });
572
+ });
projects/ui/qwen-code/packages/core/src/utils/retry.ts ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { AuthType } from '../core/contentGenerator.js';
8
+ import {
9
+ isProQuotaExceededError,
10
+ isGenericQuotaExceededError,
11
+ isQwenQuotaExceededError,
12
+ isQwenThrottlingError,
13
+ } from './quotaErrorDetection.js';
14
+
15
+ export interface HttpError extends Error {
16
+ status?: number;
17
+ }
18
+
19
+ export interface RetryOptions {
20
+ maxAttempts: number;
21
+ initialDelayMs: number;
22
+ maxDelayMs: number;
23
+ shouldRetry: (error: Error) => boolean;
24
+ onPersistent429?: (
25
+ authType?: string,
26
+ error?: unknown,
27
+ ) => Promise<string | boolean | null>;
28
+ authType?: string;
29
+ }
30
+
31
+ const DEFAULT_RETRY_OPTIONS: RetryOptions = {
32
+ maxAttempts: 5,
33
+ initialDelayMs: 5000,
34
+ maxDelayMs: 30000, // 30 seconds
35
+ shouldRetry: defaultShouldRetry,
36
+ };
37
+
38
+ /**
39
+ * Default predicate function to determine if a retry should be attempted.
40
+ * Retries on 429 (Too Many Requests) and 5xx server errors.
41
+ * @param error The error object.
42
+ * @returns True if the error is a transient error, false otherwise.
43
+ */
44
+ function defaultShouldRetry(error: Error | unknown): boolean {
45
+ // Check for common transient error status codes either in message or a status property
46
+ if (error && typeof (error as { status?: number }).status === 'number') {
47
+ const status = (error as { status: number }).status;
48
+ if (status === 429 || (status >= 500 && status < 600)) {
49
+ return true;
50
+ }
51
+ }
52
+ if (error instanceof Error && error.message) {
53
+ if (error.message.includes('429')) return true;
54
+ if (error.message.match(/5\d{2}/)) return true;
55
+ }
56
+ return false;
57
+ }
58
+
59
+ /**
60
+ * Delays execution for a specified number of milliseconds.
61
+ * @param ms The number of milliseconds to delay.
62
+ * @returns A promise that resolves after the delay.
63
+ */
64
+ function delay(ms: number): Promise<void> {
65
+ return new Promise((resolve) => setTimeout(resolve, ms));
66
+ }
67
+
68
+ /**
69
+ * Retries a function with exponential backoff and jitter.
70
+ * @param fn The asynchronous function to retry.
71
+ * @param options Optional retry configuration.
72
+ * @returns A promise that resolves with the result of the function if successful.
73
+ * @throws The last error encountered if all attempts fail.
74
+ */
75
+ export async function retryWithBackoff<T>(
76
+ fn: () => Promise<T>,
77
+ options?: Partial<RetryOptions>,
78
+ ): Promise<T> {
79
+ const {
80
+ maxAttempts,
81
+ initialDelayMs,
82
+ maxDelayMs,
83
+ onPersistent429,
84
+ authType,
85
+ shouldRetry,
86
+ } = {
87
+ ...DEFAULT_RETRY_OPTIONS,
88
+ ...options,
89
+ };
90
+
91
+ let attempt = 0;
92
+ let currentDelay = initialDelayMs;
93
+ let consecutive429Count = 0;
94
+
95
+ while (attempt < maxAttempts) {
96
+ attempt++;
97
+ try {
98
+ return await fn();
99
+ } catch (error) {
100
+ const errorStatus = getErrorStatus(error);
101
+
102
+ // Check for Pro quota exceeded error first - immediate fallback for OAuth users
103
+ if (
104
+ errorStatus === 429 &&
105
+ authType === AuthType.LOGIN_WITH_GOOGLE &&
106
+ isProQuotaExceededError(error) &&
107
+ onPersistent429
108
+ ) {
109
+ try {
110
+ const fallbackModel = await onPersistent429(authType, error);
111
+ if (fallbackModel !== false && fallbackModel !== null) {
112
+ // Reset attempt counter and try with new model
113
+ attempt = 0;
114
+ consecutive429Count = 0;
115
+ currentDelay = initialDelayMs;
116
+ // With the model updated, we continue to the next attempt
117
+ continue;
118
+ } else {
119
+ // Fallback handler returned null/false, meaning don't continue - stop retry process
120
+ throw error;
121
+ }
122
+ } catch (fallbackError) {
123
+ // If fallback fails, continue with original error
124
+ console.warn('Fallback to Flash model failed:', fallbackError);
125
+ }
126
+ }
127
+
128
+ // Check for generic quota exceeded error (but not Pro, which was handled above) - immediate fallback for OAuth users
129
+ if (
130
+ errorStatus === 429 &&
131
+ authType === AuthType.LOGIN_WITH_GOOGLE &&
132
+ !isProQuotaExceededError(error) &&
133
+ isGenericQuotaExceededError(error) &&
134
+ onPersistent429
135
+ ) {
136
+ try {
137
+ const fallbackModel = await onPersistent429(authType, error);
138
+ if (fallbackModel !== false && fallbackModel !== null) {
139
+ // Reset attempt counter and try with new model
140
+ attempt = 0;
141
+ consecutive429Count = 0;
142
+ currentDelay = initialDelayMs;
143
+ // With the model updated, we continue to the next attempt
144
+ continue;
145
+ } else {
146
+ // Fallback handler returned null/false, meaning don't continue - stop retry process
147
+ throw error;
148
+ }
149
+ } catch (fallbackError) {
150
+ // If fallback fails, continue with original error
151
+ console.warn('Fallback to Flash model failed:', fallbackError);
152
+ }
153
+ }
154
+
155
+ // Check for Qwen OAuth quota exceeded error - throw immediately without retry
156
+ if (authType === AuthType.QWEN_OAUTH && isQwenQuotaExceededError(error)) {
157
+ throw new Error(
158
+ `Qwen API quota exceeded: Your Qwen API quota has been exhausted. Please wait for your quota to reset.`,
159
+ );
160
+ }
161
+
162
+ // Track consecutive 429 errors, but handle Qwen throttling differently
163
+ if (errorStatus === 429) {
164
+ // For Qwen throttling errors, we still want to track them for exponential backoff
165
+ // but not for quota fallback logic (since Qwen doesn't have model fallback)
166
+ if (authType === AuthType.QWEN_OAUTH && isQwenThrottlingError(error)) {
167
+ // Keep track of 429s but reset the consecutive count to avoid fallback logic
168
+ consecutive429Count = 0;
169
+ } else {
170
+ consecutive429Count++;
171
+ }
172
+ } else {
173
+ consecutive429Count = 0;
174
+ }
175
+
176
+ // If we have persistent 429s and a fallback callback for OAuth
177
+ if (
178
+ consecutive429Count >= 2 &&
179
+ onPersistent429 &&
180
+ authType === AuthType.LOGIN_WITH_GOOGLE
181
+ ) {
182
+ try {
183
+ const fallbackModel = await onPersistent429(authType, error);
184
+ if (fallbackModel !== false && fallbackModel !== null) {
185
+ // Reset attempt counter and try with new model
186
+ attempt = 0;
187
+ consecutive429Count = 0;
188
+ currentDelay = initialDelayMs;
189
+ // With the model updated, we continue to the next attempt
190
+ continue;
191
+ } else {
192
+ // Fallback handler returned null/false, meaning don't continue - stop retry process
193
+ throw error;
194
+ }
195
+ } catch (fallbackError) {
196
+ // If fallback fails, continue with original error
197
+ console.warn('Fallback to Flash model failed:', fallbackError);
198
+ }
199
+ }
200
+
201
+ // Check if we've exhausted retries or shouldn't retry
202
+ if (attempt >= maxAttempts || !shouldRetry(error as Error)) {
203
+ throw error;
204
+ }
205
+
206
+ const { delayDurationMs, errorStatus: delayErrorStatus } =
207
+ getDelayDurationAndStatus(error);
208
+
209
+ if (delayDurationMs > 0) {
210
+ // Respect Retry-After header if present and parsed
211
+ console.warn(
212
+ `Attempt ${attempt} failed with status ${delayErrorStatus ?? 'unknown'}. Retrying after explicit delay of ${delayDurationMs}ms...`,
213
+ error,
214
+ );
215
+ await delay(delayDurationMs);
216
+ // Reset currentDelay for next potential non-429 error, or if Retry-After is not present next time
217
+ currentDelay = initialDelayMs;
218
+ } else {
219
+ // Fall back to exponential backoff with jitter
220
+ logRetryAttempt(attempt, error, errorStatus);
221
+ // Add jitter: +/- 30% of currentDelay
222
+ const jitter = currentDelay * 0.3 * (Math.random() * 2 - 1);
223
+ const delayWithJitter = Math.max(0, currentDelay + jitter);
224
+ await delay(delayWithJitter);
225
+ currentDelay = Math.min(maxDelayMs, currentDelay * 2);
226
+ }
227
+ }
228
+ }
229
+ // This line should theoretically be unreachable due to the throw in the catch block.
230
+ // Added for type safety and to satisfy the compiler that a promise is always returned.
231
+ throw new Error('Retry attempts exhausted');
232
+ }
233
+
234
+ /**
235
+ * Extracts the HTTP status code from an error object.
236
+ * @param error The error object.
237
+ * @returns The HTTP status code, or undefined if not found.
238
+ */
239
+ export function getErrorStatus(error: unknown): number | undefined {
240
+ if (typeof error === 'object' && error !== null) {
241
+ if ('status' in error && typeof error.status === 'number') {
242
+ return error.status;
243
+ }
244
+ // Check for error.response.status (common in axios errors)
245
+ if (
246
+ 'response' in error &&
247
+ typeof (error as { response?: unknown }).response === 'object' &&
248
+ (error as { response?: unknown }).response !== null
249
+ ) {
250
+ const response = (
251
+ error as { response: { status?: unknown; headers?: unknown } }
252
+ ).response;
253
+ if ('status' in response && typeof response.status === 'number') {
254
+ return response.status;
255
+ }
256
+ }
257
+ }
258
+ return undefined;
259
+ }
260
+
261
+ /**
262
+ * Extracts the Retry-After delay from an error object's headers.
263
+ * @param error The error object.
264
+ * @returns The delay in milliseconds, or 0 if not found or invalid.
265
+ */
266
+ function getRetryAfterDelayMs(error: unknown): number {
267
+ if (typeof error === 'object' && error !== null) {
268
+ // Check for error.response.headers (common in axios errors)
269
+ if (
270
+ 'response' in error &&
271
+ typeof (error as { response?: unknown }).response === 'object' &&
272
+ (error as { response?: unknown }).response !== null
273
+ ) {
274
+ const response = (error as { response: { headers?: unknown } }).response;
275
+ if (
276
+ 'headers' in response &&
277
+ typeof response.headers === 'object' &&
278
+ response.headers !== null
279
+ ) {
280
+ const headers = response.headers as { 'retry-after'?: unknown };
281
+ const retryAfterHeader = headers['retry-after'];
282
+ if (typeof retryAfterHeader === 'string') {
283
+ const retryAfterSeconds = parseInt(retryAfterHeader, 10);
284
+ if (!isNaN(retryAfterSeconds)) {
285
+ return retryAfterSeconds * 1000;
286
+ }
287
+ // It might be an HTTP date
288
+ const retryAfterDate = new Date(retryAfterHeader);
289
+ if (!isNaN(retryAfterDate.getTime())) {
290
+ return Math.max(0, retryAfterDate.getTime() - Date.now());
291
+ }
292
+ }
293
+ }
294
+ }
295
+ }
296
+ return 0;
297
+ }
298
+
299
+ /**
300
+ * Determines the delay duration based on the error, prioritizing Retry-After header.
301
+ * @param error The error object.
302
+ * @returns An object containing the delay duration in milliseconds and the error status.
303
+ */
304
+ function getDelayDurationAndStatus(error: unknown): {
305
+ delayDurationMs: number;
306
+ errorStatus: number | undefined;
307
+ } {
308
+ const errorStatus = getErrorStatus(error);
309
+ let delayDurationMs = 0;
310
+
311
+ if (errorStatus === 429) {
312
+ delayDurationMs = getRetryAfterDelayMs(error);
313
+ }
314
+ return { delayDurationMs, errorStatus };
315
+ }
316
+
317
+ /**
318
+ * Logs a message for a retry attempt when using exponential backoff.
319
+ * @param attempt The current attempt number.
320
+ * @param error The error that caused the retry.
321
+ * @param errorStatus The HTTP status code of the error, if available.
322
+ */
323
+ function logRetryAttempt(
324
+ attempt: number,
325
+ error: unknown,
326
+ errorStatus?: number,
327
+ ): void {
328
+ let message = `Attempt ${attempt} failed. Retrying with backoff...`;
329
+ if (errorStatus) {
330
+ message = `Attempt ${attempt} failed with status ${errorStatus}. Retrying with backoff...`;
331
+ }
332
+
333
+ if (errorStatus === 429) {
334
+ console.warn(message, error);
335
+ } else if (errorStatus && errorStatus >= 500 && errorStatus < 600) {
336
+ console.error(message, error);
337
+ } else if (error instanceof Error) {
338
+ // Fallback for errors that might not have a status but have a message
339
+ if (error.message.includes('429')) {
340
+ console.warn(
341
+ `Attempt ${attempt} failed with 429 error (no Retry-After header). Retrying with backoff...`,
342
+ error,
343
+ );
344
+ } else if (error.message.match(/5\d{2}/)) {
345
+ console.error(
346
+ `Attempt ${attempt} failed with 5xx error. Retrying with backoff...`,
347
+ error,
348
+ );
349
+ } else {
350
+ console.warn(message, error); // Default to warn for other errors
351
+ }
352
+ } else {
353
+ console.warn(message, error); // Default to warn if error type is unknown
354
+ }
355
+ }
projects/ui/qwen-code/packages/core/src/utils/safeJsonParse.test.ts ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { safeJsonParse } from './safeJsonParse.js';
9
+
10
+ describe('safeJsonParse', () => {
11
+ beforeEach(() => {
12
+ vi.clearAllMocks();
13
+ });
14
+
15
+ afterEach(() => {
16
+ vi.restoreAllMocks();
17
+ });
18
+
19
+ describe('valid JSON parsing', () => {
20
+ it('should parse valid JSON correctly', () => {
21
+ const validJson = '{"name": "test", "value": 123}';
22
+ const result = safeJsonParse(validJson);
23
+
24
+ expect(result).toEqual({ name: 'test', value: 123 });
25
+ });
26
+
27
+ it('should parse valid JSON arrays', () => {
28
+ const validArray = '["item1", "item2", "item3"]';
29
+ const result = safeJsonParse(validArray);
30
+
31
+ expect(result).toEqual(['item1', 'item2', 'item3']);
32
+ });
33
+
34
+ it('should parse valid JSON with nested objects', () => {
35
+ const validNested =
36
+ '{"config": {"paths": ["testlogs/*.py"], "options": {"recursive": true}}}';
37
+ const result = safeJsonParse(validNested);
38
+
39
+ expect(result).toEqual({
40
+ config: {
41
+ paths: ['testlogs/*.py'],
42
+ options: { recursive: true },
43
+ },
44
+ });
45
+ });
46
+ });
47
+
48
+ describe('malformed JSON with jsonrepair fallback', () => {
49
+ it('should handle malformed JSON with single quotes', () => {
50
+ const malformedJson = "{'name': 'test', 'value': 123}";
51
+ const result = safeJsonParse(malformedJson);
52
+
53
+ expect(result).toEqual({ name: 'test', value: 123 });
54
+ });
55
+
56
+ it('should handle malformed JSON with unquoted keys', () => {
57
+ const malformedJson = '{name: "test", value: 123}';
58
+ const result = safeJsonParse(malformedJson);
59
+
60
+ expect(result).toEqual({ name: 'test', value: 123 });
61
+ });
62
+
63
+ it('should handle malformed JSON with trailing commas', () => {
64
+ const malformedJson = '{"name": "test", "value": 123,}';
65
+ const result = safeJsonParse(malformedJson);
66
+
67
+ expect(result).toEqual({ name: 'test', value: 123 });
68
+ });
69
+
70
+ it('should handle malformed JSON with comments', () => {
71
+ const malformedJson = '{"name": "test", // comment\n "value": 123}';
72
+ const result = safeJsonParse(malformedJson);
73
+
74
+ expect(result).toEqual({ name: 'test', value: 123 });
75
+ });
76
+ });
77
+
78
+ describe('fallback behavior', () => {
79
+ it('should return fallback value for empty string', () => {
80
+ const emptyString = '';
81
+ const fallback = { default: 'value' };
82
+
83
+ const result = safeJsonParse(emptyString, fallback);
84
+
85
+ expect(result).toEqual(fallback);
86
+ });
87
+
88
+ it('should return fallback value for null input', () => {
89
+ const nullInput = null as unknown as string;
90
+ const fallback = { default: 'value' };
91
+
92
+ const result = safeJsonParse(nullInput, fallback);
93
+
94
+ expect(result).toEqual(fallback);
95
+ });
96
+
97
+ it('should return fallback value for undefined input', () => {
98
+ const undefinedInput = undefined as unknown as string;
99
+ const fallback = { default: 'value' };
100
+
101
+ const result = safeJsonParse(undefinedInput, fallback);
102
+
103
+ expect(result).toEqual(fallback);
104
+ });
105
+
106
+ it('should return empty object as default fallback', () => {
107
+ const invalidJson = 'invalid json';
108
+
109
+ const result = safeJsonParse(invalidJson);
110
+
111
+ // jsonrepair returns the original string for completely invalid JSON
112
+ expect(result).toEqual('invalid json');
113
+ });
114
+
115
+ it('should return custom fallback when parsing fails', () => {
116
+ const invalidJson = 'invalid json';
117
+ const customFallback = { error: 'parsing failed', data: null };
118
+
119
+ const result = safeJsonParse(invalidJson, customFallback);
120
+
121
+ // jsonrepair returns the original string for completely invalid JSON
122
+ expect(result).toEqual('invalid json');
123
+ });
124
+ });
125
+
126
+ describe('type safety', () => {
127
+ it('should preserve generic type when parsing valid JSON', () => {
128
+ const validJson = '{"name": "test", "value": 123}';
129
+ const result = safeJsonParse<{ name: string; value: number }>(validJson);
130
+
131
+ expect(result).toEqual({ name: 'test', value: 123 });
132
+ // TypeScript should infer the correct type
133
+ expect(typeof result.name).toBe('string');
134
+ expect(typeof result.value).toBe('number');
135
+ });
136
+
137
+ it('should return fallback type when parsing fails', () => {
138
+ const invalidJson = 'invalid json';
139
+ const fallback = { error: 'fallback' } as const;
140
+
141
+ const result = safeJsonParse(invalidJson, fallback);
142
+
143
+ // jsonrepair returns the original string for completely invalid JSON
144
+ expect(result).toEqual('invalid json');
145
+ // TypeScript should preserve the fallback type
146
+ expect(typeof result).toBe('string');
147
+ });
148
+ });
149
+ });
projects/ui/qwen-code/packages/core/src/utils/safeJsonParse.ts ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { jsonrepair } from 'jsonrepair';
8
+
9
+ /**
10
+ * Safely parse JSON string with jsonrepair fallback for malformed JSON.
11
+ * This function attempts to parse JSON normally first, and if that fails,
12
+ * it uses jsonrepair to fix common JSON formatting issues before parsing.
13
+ *
14
+ * @param jsonString - The JSON string to parse
15
+ * @param fallbackValue - The value to return if parsing fails completely
16
+ * @returns The parsed object or the fallback value
17
+ */
18
+ export function safeJsonParse<T = Record<string, unknown>>(
19
+ jsonString: string,
20
+ fallbackValue: T = {} as T,
21
+ ): T {
22
+ if (!jsonString || typeof jsonString !== 'string') {
23
+ return fallbackValue;
24
+ }
25
+
26
+ try {
27
+ // First attempt: try normal JSON.parse
28
+ return JSON.parse(jsonString) as T;
29
+ } catch (error) {
30
+ try {
31
+ // Second attempt: use jsonrepair to fix common JSON issues
32
+ const repairedJson = jsonrepair(jsonString);
33
+
34
+ // jsonrepair always returns a string, so we need to parse it
35
+ return JSON.parse(repairedJson) as T;
36
+ } catch (repairError) {
37
+ console.error('Failed to parse JSON even with jsonrepair:', {
38
+ originalError: error,
39
+ repairError,
40
+ jsonString,
41
+ });
42
+ return fallbackValue;
43
+ }
44
+ }
45
+ }