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

Add files using upload-large-folder tool

Browse files
projects/ui/qwen-code/packages/core/src/utils/safeJsonStringify.test.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 { describe, it, expect } from 'vitest';
8
+ import { safeJsonStringify } from './safeJsonStringify.js';
9
+
10
+ describe('safeJsonStringify', () => {
11
+ it('should stringify normal objects without issues', () => {
12
+ const obj = { name: 'test', value: 42 };
13
+ const result = safeJsonStringify(obj);
14
+ expect(result).toBe('{"name":"test","value":42}');
15
+ });
16
+
17
+ it('should handle circular references by replacing them with [Circular]', () => {
18
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
19
+ const obj: any = { name: 'test' };
20
+ obj.circular = obj; // Create circular reference
21
+
22
+ const result = safeJsonStringify(obj);
23
+ expect(result).toBe('{"name":"test","circular":"[Circular]"}');
24
+ });
25
+
26
+ it('should handle complex circular structures like HttpsProxyAgent', () => {
27
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
28
+ const agent: any = {
29
+ sockets: {},
30
+ options: { host: 'example.com' },
31
+ };
32
+ agent.sockets['example.com'] = [{ agent }];
33
+
34
+ const result = safeJsonStringify(agent);
35
+ expect(result).toContain('[Circular]');
36
+ expect(result).toContain('example.com');
37
+ });
38
+
39
+ it('should respect the space parameter for formatting', () => {
40
+ const obj = { name: 'test', value: 42 };
41
+ const result = safeJsonStringify(obj, 2);
42
+ expect(result).toBe('{\n "name": "test",\n "value": 42\n}');
43
+ });
44
+
45
+ it('should handle circular references with formatting', () => {
46
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
47
+ const obj: any = { name: 'test' };
48
+ obj.circular = obj;
49
+
50
+ const result = safeJsonStringify(obj, 2);
51
+ expect(result).toBe('{\n "name": "test",\n "circular": "[Circular]"\n}');
52
+ });
53
+
54
+ it('should handle arrays with circular references', () => {
55
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
+ const arr: any[] = [{ id: 1 }];
57
+ arr[0].parent = arr; // Create circular reference
58
+
59
+ const result = safeJsonStringify(arr);
60
+ expect(result).toBe('[{"id":1,"parent":"[Circular]"}]');
61
+ });
62
+
63
+ it('should handle null and undefined values', () => {
64
+ expect(safeJsonStringify(null)).toBe('null');
65
+ expect(safeJsonStringify(undefined)).toBe(undefined);
66
+ });
67
+
68
+ it('should handle primitive values', () => {
69
+ expect(safeJsonStringify('test')).toBe('"test"');
70
+ expect(safeJsonStringify(42)).toBe('42');
71
+ expect(safeJsonStringify(true)).toBe('true');
72
+ });
73
+ });
projects/ui/qwen-code/packages/core/src/utils/safeJsonStringify.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * Safely stringifies an object to JSON, handling circular references by replacing them with [Circular].
9
+ *
10
+ * @param obj - The object to stringify
11
+ * @param space - Optional space parameter for formatting (defaults to no formatting)
12
+ * @returns JSON string with circular references replaced by [Circular]
13
+ */
14
+ export function safeJsonStringify(
15
+ obj: unknown,
16
+ space?: string | number,
17
+ ): string {
18
+ const seen = new WeakSet();
19
+ return JSON.stringify(
20
+ obj,
21
+ (key, value) => {
22
+ if (typeof value === 'object' && value !== null) {
23
+ if (seen.has(value)) {
24
+ return '[Circular]';
25
+ }
26
+ seen.add(value);
27
+ }
28
+ return value;
29
+ },
30
+ space,
31
+ );
32
+ }
projects/ui/qwen-code/packages/core/src/utils/schemaValidator.ts ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import AjvPkg from 'ajv';
8
+ // Ajv's ESM/CJS interop: use 'any' for compatibility as recommended by Ajv docs
9
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
10
+ const AjvClass = (AjvPkg as any).default || AjvPkg;
11
+ const ajValidator = new AjvClass();
12
+
13
+ /**
14
+ * Simple utility to validate objects against JSON Schemas
15
+ */
16
+ export class SchemaValidator {
17
+ /**
18
+ * Returns null if the data confroms to the schema described by schema (or if schema
19
+ * is null). Otherwise, returns a string describing the error.
20
+ */
21
+ static validate(schema: unknown | undefined, data: unknown): string | null {
22
+ if (!schema) {
23
+ return null;
24
+ }
25
+ if (typeof data !== 'object' || data === null) {
26
+ return 'Value of params must be an object';
27
+ }
28
+ const validate = ajValidator.compile(schema);
29
+ const valid = validate(data);
30
+ if (!valid && validate.errors) {
31
+ return ajValidator.errorsText(validate.errors, { dataVar: 'params' });
32
+ }
33
+ return null;
34
+ }
35
+ }
projects/ui/qwen-code/packages/core/src/utils/secure-browser-launcher.test.ts ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
8
+ import { openBrowserSecurely } from './secure-browser-launcher.js';
9
+
10
+ // Create mock function using vi.hoisted
11
+ const mockExecFile = vi.hoisted(() => vi.fn());
12
+
13
+ // Mock modules
14
+ vi.mock('node:child_process');
15
+ vi.mock('node:util', () => ({
16
+ promisify: () => mockExecFile,
17
+ }));
18
+
19
+ describe('secure-browser-launcher', () => {
20
+ let originalPlatform: PropertyDescriptor | undefined;
21
+
22
+ beforeEach(() => {
23
+ vi.clearAllMocks();
24
+ mockExecFile.mockResolvedValue({ stdout: '', stderr: '' });
25
+ originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform');
26
+ });
27
+
28
+ afterEach(() => {
29
+ if (originalPlatform) {
30
+ Object.defineProperty(process, 'platform', originalPlatform);
31
+ }
32
+ });
33
+
34
+ function setPlatform(platform: string) {
35
+ Object.defineProperty(process, 'platform', {
36
+ value: platform,
37
+ configurable: true,
38
+ });
39
+ }
40
+
41
+ describe('URL validation', () => {
42
+ it('should allow valid HTTP URLs', async () => {
43
+ setPlatform('darwin');
44
+ await openBrowserSecurely('http://example.com');
45
+ expect(mockExecFile).toHaveBeenCalledWith(
46
+ 'open',
47
+ ['http://example.com'],
48
+ expect.any(Object),
49
+ );
50
+ });
51
+
52
+ it('should allow valid HTTPS URLs', async () => {
53
+ setPlatform('darwin');
54
+ await openBrowserSecurely('https://example.com');
55
+ expect(mockExecFile).toHaveBeenCalledWith(
56
+ 'open',
57
+ ['https://example.com'],
58
+ expect.any(Object),
59
+ );
60
+ });
61
+
62
+ it('should reject non-HTTP(S) protocols', async () => {
63
+ await expect(openBrowserSecurely('file:///etc/passwd')).rejects.toThrow(
64
+ 'Unsafe protocol',
65
+ );
66
+ await expect(openBrowserSecurely('javascript:alert(1)')).rejects.toThrow(
67
+ 'Unsafe protocol',
68
+ );
69
+ await expect(openBrowserSecurely('ftp://example.com')).rejects.toThrow(
70
+ 'Unsafe protocol',
71
+ );
72
+ });
73
+
74
+ it('should reject invalid URLs', async () => {
75
+ await expect(openBrowserSecurely('not-a-url')).rejects.toThrow(
76
+ 'Invalid URL',
77
+ );
78
+ await expect(openBrowserSecurely('')).rejects.toThrow('Invalid URL');
79
+ });
80
+
81
+ it('should reject URLs with control characters', async () => {
82
+ await expect(
83
+ openBrowserSecurely('http://example.com\nmalicious-command'),
84
+ ).rejects.toThrow('invalid characters');
85
+ await expect(
86
+ openBrowserSecurely('http://example.com\rmalicious-command'),
87
+ ).rejects.toThrow('invalid characters');
88
+ await expect(
89
+ openBrowserSecurely('http://example.com\x00'),
90
+ ).rejects.toThrow('invalid characters');
91
+ });
92
+ });
93
+
94
+ describe('Command injection prevention', () => {
95
+ it('should prevent PowerShell command injection on Windows', async () => {
96
+ setPlatform('win32');
97
+
98
+ // The POC from the vulnerability report
99
+ const maliciousUrl =
100
+ "http://127.0.0.1:8080/?param=example#$(Invoke-Expression([System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('Y2FsYy5leGU='))))";
101
+
102
+ await openBrowserSecurely(maliciousUrl);
103
+
104
+ // Verify that execFile was called (not exec) and the URL is passed safely
105
+ expect(mockExecFile).toHaveBeenCalledWith(
106
+ 'powershell.exe',
107
+ [
108
+ '-NoProfile',
109
+ '-NonInteractive',
110
+ '-WindowStyle',
111
+ 'Hidden',
112
+ '-Command',
113
+ `Start-Process '${maliciousUrl.replace(/'/g, "''")}'`,
114
+ ],
115
+ expect.any(Object),
116
+ );
117
+ });
118
+
119
+ it('should handle URLs with special shell characters safely', async () => {
120
+ setPlatform('darwin');
121
+
122
+ const urlsWithSpecialChars = [
123
+ 'http://example.com/path?param=value&other=$value',
124
+ 'http://example.com/path#fragment;command',
125
+ 'http://example.com/$(whoami)',
126
+ 'http://example.com/`command`',
127
+ 'http://example.com/|pipe',
128
+ 'http://example.com/>redirect',
129
+ ];
130
+
131
+ for (const url of urlsWithSpecialChars) {
132
+ await openBrowserSecurely(url);
133
+ // Verify the URL is passed as an argument, not interpreted by shell
134
+ expect(mockExecFile).toHaveBeenCalledWith(
135
+ 'open',
136
+ [url],
137
+ expect.any(Object),
138
+ );
139
+ }
140
+ });
141
+
142
+ it('should properly escape single quotes in URLs on Windows', async () => {
143
+ setPlatform('win32');
144
+
145
+ const urlWithSingleQuotes =
146
+ "http://example.com/path?name=O'Brien&test='value'";
147
+ await openBrowserSecurely(urlWithSingleQuotes);
148
+
149
+ // Verify that single quotes are escaped by doubling them
150
+ expect(mockExecFile).toHaveBeenCalledWith(
151
+ 'powershell.exe',
152
+ [
153
+ '-NoProfile',
154
+ '-NonInteractive',
155
+ '-WindowStyle',
156
+ 'Hidden',
157
+ '-Command',
158
+ `Start-Process 'http://example.com/path?name=O''Brien&test=''value'''`,
159
+ ],
160
+ expect.any(Object),
161
+ );
162
+ });
163
+ });
164
+
165
+ describe('Platform-specific behavior', () => {
166
+ it('should use correct command on macOS', async () => {
167
+ setPlatform('darwin');
168
+ await openBrowserSecurely('https://example.com');
169
+ expect(mockExecFile).toHaveBeenCalledWith(
170
+ 'open',
171
+ ['https://example.com'],
172
+ expect.any(Object),
173
+ );
174
+ });
175
+
176
+ it('should use PowerShell on Windows', async () => {
177
+ setPlatform('win32');
178
+ await openBrowserSecurely('https://example.com');
179
+ expect(mockExecFile).toHaveBeenCalledWith(
180
+ 'powershell.exe',
181
+ expect.arrayContaining([
182
+ '-Command',
183
+ `Start-Process 'https://example.com'`,
184
+ ]),
185
+ expect.any(Object),
186
+ );
187
+ });
188
+
189
+ it('should use xdg-open on Linux', async () => {
190
+ setPlatform('linux');
191
+ await openBrowserSecurely('https://example.com');
192
+ expect(mockExecFile).toHaveBeenCalledWith(
193
+ 'xdg-open',
194
+ ['https://example.com'],
195
+ expect.any(Object),
196
+ );
197
+ });
198
+
199
+ it('should throw on unsupported platforms', async () => {
200
+ setPlatform('aix');
201
+ await expect(openBrowserSecurely('https://example.com')).rejects.toThrow(
202
+ 'Unsupported platform',
203
+ );
204
+ });
205
+ });
206
+
207
+ describe('Error handling', () => {
208
+ it('should handle browser launch failures gracefully', async () => {
209
+ setPlatform('darwin');
210
+ mockExecFile.mockRejectedValueOnce(new Error('Command not found'));
211
+
212
+ await expect(openBrowserSecurely('https://example.com')).rejects.toThrow(
213
+ 'Failed to open browser',
214
+ );
215
+ });
216
+
217
+ it('should try fallback browsers on Linux', async () => {
218
+ setPlatform('linux');
219
+
220
+ // First call to xdg-open fails
221
+ mockExecFile.mockRejectedValueOnce(new Error('Command not found'));
222
+ // Second call to gnome-open succeeds
223
+ mockExecFile.mockResolvedValueOnce({ stdout: '', stderr: '' });
224
+
225
+ await openBrowserSecurely('https://example.com');
226
+
227
+ expect(mockExecFile).toHaveBeenCalledTimes(2);
228
+ expect(mockExecFile).toHaveBeenNthCalledWith(
229
+ 1,
230
+ 'xdg-open',
231
+ ['https://example.com'],
232
+ expect.any(Object),
233
+ );
234
+ expect(mockExecFile).toHaveBeenNthCalledWith(
235
+ 2,
236
+ 'gnome-open',
237
+ ['https://example.com'],
238
+ expect.any(Object),
239
+ );
240
+ });
241
+ });
242
+ });
projects/ui/qwen-code/packages/core/src/utils/secure-browser-launcher.ts ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { execFile } from 'node:child_process';
8
+ import { promisify } from 'node:util';
9
+ import { platform } from 'node:os';
10
+ import { URL } from 'node:url';
11
+
12
+ const execFileAsync = promisify(execFile);
13
+
14
+ /**
15
+ * Validates that a URL is safe to open in a browser.
16
+ * Only allows HTTP and HTTPS URLs to prevent command injection.
17
+ *
18
+ * @param url The URL to validate
19
+ * @throws Error if the URL is invalid or uses an unsafe protocol
20
+ */
21
+ function validateUrl(url: string): void {
22
+ let parsedUrl: URL;
23
+
24
+ try {
25
+ parsedUrl = new URL(url);
26
+ } catch (_error) {
27
+ throw new Error(`Invalid URL: ${url}`);
28
+ }
29
+
30
+ // Only allow HTTP and HTTPS protocols
31
+ if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
32
+ throw new Error(
33
+ `Unsafe protocol: ${parsedUrl.protocol}. Only HTTP and HTTPS are allowed.`,
34
+ );
35
+ }
36
+
37
+ // Additional validation: ensure no newlines or control characters
38
+ // eslint-disable-next-line no-control-regex
39
+ if (/[\r\n\x00-\x1f]/.test(url)) {
40
+ throw new Error('URL contains invalid characters');
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Opens a URL in the default browser using platform-specific commands.
46
+ * This implementation avoids shell injection vulnerabilities by:
47
+ * 1. Validating the URL to ensure it's HTTP/HTTPS only
48
+ * 2. Using execFile instead of exec to avoid shell interpretation
49
+ * 3. Passing the URL as an argument rather than constructing a command string
50
+ *
51
+ * @param url The URL to open
52
+ * @throws Error if the URL is invalid or if opening the browser fails
53
+ */
54
+ export async function openBrowserSecurely(url: string): Promise<void> {
55
+ // Validate the URL first
56
+ validateUrl(url);
57
+
58
+ const platformName = platform();
59
+ let command: string;
60
+ let args: string[];
61
+
62
+ switch (platformName) {
63
+ case 'darwin':
64
+ // macOS
65
+ command = 'open';
66
+ args = [url];
67
+ break;
68
+
69
+ case 'win32':
70
+ // Windows - use PowerShell with Start-Process
71
+ // This avoids the cmd.exe shell which is vulnerable to injection
72
+ command = 'powershell.exe';
73
+ args = [
74
+ '-NoProfile',
75
+ '-NonInteractive',
76
+ '-WindowStyle',
77
+ 'Hidden',
78
+ '-Command',
79
+ `Start-Process '${url.replace(/'/g, "''")}'`,
80
+ ];
81
+ break;
82
+
83
+ case 'linux':
84
+ case 'freebsd':
85
+ case 'openbsd':
86
+ // Linux and BSD variants
87
+ // Try xdg-open first, fall back to other options
88
+ command = 'xdg-open';
89
+ args = [url];
90
+ break;
91
+
92
+ default:
93
+ throw new Error(`Unsupported platform: ${platformName}`);
94
+ }
95
+
96
+ const options: Record<string, unknown> = {
97
+ // Don't inherit parent's environment to avoid potential issues
98
+ env: {
99
+ ...process.env,
100
+ // Ensure we're not in a shell that might interpret special characters
101
+ SHELL: undefined,
102
+ },
103
+ // Detach the browser process so it doesn't block
104
+ detached: true,
105
+ stdio: 'ignore',
106
+ };
107
+
108
+ try {
109
+ await execFileAsync(command, args, options);
110
+ } catch (error) {
111
+ // For Linux, try fallback commands if xdg-open fails
112
+ if (
113
+ (platformName === 'linux' ||
114
+ platformName === 'freebsd' ||
115
+ platformName === 'openbsd') &&
116
+ command === 'xdg-open'
117
+ ) {
118
+ const fallbackCommands = [
119
+ 'gnome-open',
120
+ 'kde-open',
121
+ 'firefox',
122
+ 'chromium',
123
+ 'google-chrome',
124
+ ];
125
+
126
+ for (const fallbackCommand of fallbackCommands) {
127
+ try {
128
+ await execFileAsync(fallbackCommand, [url], options);
129
+ return; // Success!
130
+ } catch {
131
+ // Try next command
132
+ continue;
133
+ }
134
+ }
135
+ }
136
+
137
+ // Re-throw the error if all attempts failed
138
+ throw new Error(
139
+ `Failed to open browser: ${error instanceof Error ? error.message : 'Unknown error'}`,
140
+ );
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Checks if the current environment should attempt to launch a browser.
146
+ * This is the same logic as in browser.ts for consistency.
147
+ *
148
+ * @returns True if the tool should attempt to launch a browser
149
+ */
150
+ export function shouldLaunchBrowser(): boolean {
151
+ // A list of browser names that indicate we should not attempt to open a
152
+ // web browser for the user.
153
+ const browserBlocklist = ['www-browser'];
154
+ const browserEnv = process.env['BROWSER'];
155
+ if (browserEnv && browserBlocklist.includes(browserEnv)) {
156
+ return false;
157
+ }
158
+
159
+ // Common environment variables used in CI/CD or other non-interactive shells.
160
+ if (
161
+ process.env['CI'] ||
162
+ process.env['DEBIAN_FRONTEND'] === 'noninteractive'
163
+ ) {
164
+ return false;
165
+ }
166
+
167
+ // The presence of SSH_CONNECTION indicates a remote session.
168
+ // We should not attempt to launch a browser unless a display is explicitly available
169
+ // (checked below for Linux).
170
+ const isSSH = !!process.env['SSH_CONNECTION'];
171
+
172
+ // On Linux, the presence of a display server is a strong indicator of a GUI.
173
+ if (platform() === 'linux') {
174
+ // These are environment variables that can indicate a running compositor on Linux.
175
+ const displayVariables = ['DISPLAY', 'WAYLAND_DISPLAY', 'MIR_SOCKET'];
176
+ const hasDisplay = displayVariables.some((v) => !!process.env[v]);
177
+ if (!hasDisplay) {
178
+ return false;
179
+ }
180
+ }
181
+
182
+ // If in an SSH session on a non-Linux OS (e.g., macOS), don't launch browser.
183
+ // The Linux case is handled above (it's allowed if DISPLAY is set).
184
+ if (isSSH && platform() !== 'linux') {
185
+ return false;
186
+ }
187
+
188
+ // For non-Linux OSes, we generally assume a GUI is available
189
+ // unless other signals (like SSH) suggest otherwise.
190
+ return true;
191
+ }
projects/ui/qwen-code/packages/core/src/utils/session.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { randomUUID } from 'crypto';
8
+
9
+ export const sessionId = randomUUID();
projects/ui/qwen-code/packages/core/src/utils/shell-utils.test.ts ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { expect, describe, it, beforeEach, vi, afterEach } from 'vitest';
8
+ import {
9
+ checkCommandPermissions,
10
+ escapeShellArg,
11
+ getCommandRoots,
12
+ getShellConfiguration,
13
+ isCommandAllowed,
14
+ stripShellWrapper,
15
+ } from './shell-utils.js';
16
+ import { Config } from '../config/config.js';
17
+
18
+ const mockPlatform = vi.hoisted(() => vi.fn());
19
+ vi.mock('os', () => ({
20
+ default: {
21
+ platform: mockPlatform,
22
+ },
23
+ platform: mockPlatform,
24
+ }));
25
+
26
+ const mockQuote = vi.hoisted(() => vi.fn());
27
+ vi.mock('shell-quote', () => ({
28
+ quote: mockQuote,
29
+ }));
30
+
31
+ let config: Config;
32
+
33
+ beforeEach(() => {
34
+ mockPlatform.mockReturnValue('linux');
35
+ mockQuote.mockImplementation((args: string[]) =>
36
+ args.map((arg) => `'${arg}'`).join(' '),
37
+ );
38
+ config = {
39
+ getCoreTools: () => [],
40
+ getExcludeTools: () => [],
41
+ } as unknown as Config;
42
+ });
43
+
44
+ afterEach(() => {
45
+ vi.clearAllMocks();
46
+ });
47
+
48
+ describe('isCommandAllowed', () => {
49
+ it('should allow a command if no restrictions are provided', () => {
50
+ const result = isCommandAllowed('ls -l', config);
51
+ expect(result.allowed).toBe(true);
52
+ });
53
+
54
+ it('should allow a command if it is in the global allowlist', () => {
55
+ config.getCoreTools = () => ['ShellTool(ls)'];
56
+ const result = isCommandAllowed('ls -l', config);
57
+ expect(result.allowed).toBe(true);
58
+ });
59
+
60
+ it('should block a command if it is not in a strict global allowlist', () => {
61
+ config.getCoreTools = () => ['ShellTool(ls -l)'];
62
+ const result = isCommandAllowed('rm -rf /', config);
63
+ expect(result.allowed).toBe(false);
64
+ expect(result.reason).toBe(
65
+ `Command(s) not in the allowed commands list. Disallowed commands: "rm -rf /"`,
66
+ );
67
+ });
68
+
69
+ it('should block a command if it is in the blocked list', () => {
70
+ config.getExcludeTools = () => ['ShellTool(rm -rf /)'];
71
+ const result = isCommandAllowed('rm -rf /', config);
72
+ expect(result.allowed).toBe(false);
73
+ expect(result.reason).toBe(
74
+ `Command 'rm -rf /' is blocked by configuration`,
75
+ );
76
+ });
77
+
78
+ it('should prioritize the blocklist over the allowlist', () => {
79
+ config.getCoreTools = () => ['ShellTool(rm -rf /)'];
80
+ config.getExcludeTools = () => ['ShellTool(rm -rf /)'];
81
+ const result = isCommandAllowed('rm -rf /', config);
82
+ expect(result.allowed).toBe(false);
83
+ expect(result.reason).toBe(
84
+ `Command 'rm -rf /' is blocked by configuration`,
85
+ );
86
+ });
87
+
88
+ it('should allow any command when a wildcard is in coreTools', () => {
89
+ config.getCoreTools = () => ['ShellTool'];
90
+ const result = isCommandAllowed('any random command', config);
91
+ expect(result.allowed).toBe(true);
92
+ });
93
+
94
+ it('should block any command when a wildcard is in excludeTools', () => {
95
+ config.getExcludeTools = () => ['run_shell_command'];
96
+ const result = isCommandAllowed('any random command', config);
97
+ expect(result.allowed).toBe(false);
98
+ expect(result.reason).toBe(
99
+ 'Shell tool is globally disabled in configuration',
100
+ );
101
+ });
102
+
103
+ it('should block a command on the blocklist even with a wildcard allow', () => {
104
+ config.getCoreTools = () => ['ShellTool'];
105
+ config.getExcludeTools = () => ['ShellTool(rm -rf /)'];
106
+ const result = isCommandAllowed('rm -rf /', config);
107
+ expect(result.allowed).toBe(false);
108
+ expect(result.reason).toBe(
109
+ `Command 'rm -rf /' is blocked by configuration`,
110
+ );
111
+ });
112
+
113
+ it('should allow a chained command if all parts are on the global allowlist', () => {
114
+ config.getCoreTools = () => [
115
+ 'run_shell_command(echo)',
116
+ 'run_shell_command(ls)',
117
+ ];
118
+ const result = isCommandAllowed('echo "hello" && ls -l', config);
119
+ expect(result.allowed).toBe(true);
120
+ });
121
+
122
+ it('should block a chained command if any part is blocked', () => {
123
+ config.getExcludeTools = () => ['run_shell_command(rm)'];
124
+ const result = isCommandAllowed('echo "hello" && rm -rf /', config);
125
+ expect(result.allowed).toBe(false);
126
+ expect(result.reason).toBe(
127
+ `Command 'rm -rf /' is blocked by configuration`,
128
+ );
129
+ });
130
+
131
+ describe('command substitution', () => {
132
+ it('should block command substitution using `$(...)`', () => {
133
+ const result = isCommandAllowed('echo $(rm -rf /)', config);
134
+ expect(result.allowed).toBe(false);
135
+ expect(result.reason).toContain('Command substitution');
136
+ });
137
+
138
+ it('should block command substitution using `<(...)`', () => {
139
+ const result = isCommandAllowed('diff <(ls) <(ls -a)', config);
140
+ expect(result.allowed).toBe(false);
141
+ expect(result.reason).toContain('Command substitution');
142
+ });
143
+
144
+ it('should block command substitution using backticks', () => {
145
+ const result = isCommandAllowed('echo `rm -rf /`', config);
146
+ expect(result.allowed).toBe(false);
147
+ expect(result.reason).toContain('Command substitution');
148
+ });
149
+
150
+ it('should allow substitution-like patterns inside single quotes', () => {
151
+ config.getCoreTools = () => ['ShellTool(echo)'];
152
+ const result = isCommandAllowed("echo '$(pwd)'", config);
153
+ expect(result.allowed).toBe(true);
154
+ });
155
+ });
156
+ });
157
+
158
+ describe('checkCommandPermissions', () => {
159
+ describe('in "Default Allow" mode (no sessionAllowlist)', () => {
160
+ it('should return a detailed success object for an allowed command', () => {
161
+ const result = checkCommandPermissions('ls -l', config);
162
+ expect(result).toEqual({
163
+ allAllowed: true,
164
+ disallowedCommands: [],
165
+ });
166
+ });
167
+
168
+ it('should return a detailed failure object for a blocked command', () => {
169
+ config.getExcludeTools = () => ['ShellTool(rm)'];
170
+ const result = checkCommandPermissions('rm -rf /', config);
171
+ expect(result).toEqual({
172
+ allAllowed: false,
173
+ disallowedCommands: ['rm -rf /'],
174
+ blockReason: `Command 'rm -rf /' is blocked by configuration`,
175
+ isHardDenial: true,
176
+ });
177
+ });
178
+
179
+ it('should return a detailed failure object for a command not on a strict allowlist', () => {
180
+ config.getCoreTools = () => ['ShellTool(ls)'];
181
+ const result = checkCommandPermissions('git status && ls', config);
182
+ expect(result).toEqual({
183
+ allAllowed: false,
184
+ disallowedCommands: ['git status'],
185
+ blockReason: `Command(s) not in the allowed commands list. Disallowed commands: "git status"`,
186
+ isHardDenial: false,
187
+ });
188
+ });
189
+ });
190
+
191
+ describe('in "Default Deny" mode (with sessionAllowlist)', () => {
192
+ it('should allow a command on the sessionAllowlist', () => {
193
+ const result = checkCommandPermissions(
194
+ 'ls -l',
195
+ config,
196
+ new Set(['ls -l']),
197
+ );
198
+ expect(result.allAllowed).toBe(true);
199
+ });
200
+
201
+ it('should block a command not on the sessionAllowlist or global allowlist', () => {
202
+ const result = checkCommandPermissions(
203
+ 'rm -rf /',
204
+ config,
205
+ new Set(['ls -l']),
206
+ );
207
+ expect(result.allAllowed).toBe(false);
208
+ expect(result.blockReason).toContain(
209
+ 'not on the global or session allowlist',
210
+ );
211
+ expect(result.disallowedCommands).toEqual(['rm -rf /']);
212
+ });
213
+
214
+ it('should allow a command on the global allowlist even if not on the session allowlist', () => {
215
+ config.getCoreTools = () => ['ShellTool(git status)'];
216
+ const result = checkCommandPermissions(
217
+ 'git status',
218
+ config,
219
+ new Set(['ls -l']),
220
+ );
221
+ expect(result.allAllowed).toBe(true);
222
+ });
223
+
224
+ it('should allow a chained command if parts are on different allowlists', () => {
225
+ config.getCoreTools = () => ['ShellTool(git status)'];
226
+ const result = checkCommandPermissions(
227
+ 'git status && git commit',
228
+ config,
229
+ new Set(['git commit']),
230
+ );
231
+ expect(result.allAllowed).toBe(true);
232
+ });
233
+
234
+ it('should block a command on the sessionAllowlist if it is also globally blocked', () => {
235
+ config.getExcludeTools = () => ['run_shell_command(rm)'];
236
+ const result = checkCommandPermissions(
237
+ 'rm -rf /',
238
+ config,
239
+ new Set(['rm -rf /']),
240
+ );
241
+ expect(result.allAllowed).toBe(false);
242
+ expect(result.blockReason).toContain('is blocked by configuration');
243
+ });
244
+
245
+ it('should block a chained command if one part is not on any allowlist', () => {
246
+ config.getCoreTools = () => ['run_shell_command(echo)'];
247
+ const result = checkCommandPermissions(
248
+ 'echo "hello" && rm -rf /',
249
+ config,
250
+ new Set(['echo']),
251
+ );
252
+ expect(result.allAllowed).toBe(false);
253
+ expect(result.disallowedCommands).toEqual(['rm -rf /']);
254
+ });
255
+ });
256
+ });
257
+
258
+ describe('getCommandRoots', () => {
259
+ it('should return a single command', () => {
260
+ expect(getCommandRoots('ls -l')).toEqual(['ls']);
261
+ });
262
+
263
+ it('should handle paths and return the binary name', () => {
264
+ expect(getCommandRoots('/usr/local/bin/node script.js')).toEqual(['node']);
265
+ });
266
+
267
+ it('should return an empty array for an empty string', () => {
268
+ expect(getCommandRoots('')).toEqual([]);
269
+ });
270
+
271
+ it('should handle a mix of operators', () => {
272
+ const result = getCommandRoots('a;b|c&&d||e&f');
273
+ expect(result).toEqual(['a', 'b', 'c', 'd', 'e', 'f']);
274
+ });
275
+
276
+ it('should correctly parse a chained command with quotes', () => {
277
+ const result = getCommandRoots('echo "hello" && git commit -m "feat"');
278
+ expect(result).toEqual(['echo', 'git']);
279
+ });
280
+ });
281
+
282
+ describe('stripShellWrapper', () => {
283
+ it('should strip sh -c with quotes', () => {
284
+ expect(stripShellWrapper('sh -c "ls -l"')).toEqual('ls -l');
285
+ });
286
+
287
+ it('should strip bash -c with extra whitespace', () => {
288
+ expect(stripShellWrapper(' bash -c "ls -l" ')).toEqual('ls -l');
289
+ });
290
+
291
+ it('should strip zsh -c without quotes', () => {
292
+ expect(stripShellWrapper('zsh -c ls -l')).toEqual('ls -l');
293
+ });
294
+
295
+ it('should strip cmd.exe /c', () => {
296
+ expect(stripShellWrapper('cmd.exe /c "dir"')).toEqual('dir');
297
+ });
298
+
299
+ it('should not strip anything if no wrapper is present', () => {
300
+ expect(stripShellWrapper('ls -l')).toEqual('ls -l');
301
+ });
302
+ });
303
+
304
+ describe('escapeShellArg', () => {
305
+ describe('POSIX (bash)', () => {
306
+ it('should use shell-quote for escaping', () => {
307
+ mockQuote.mockReturnValueOnce("'escaped value'");
308
+ const result = escapeShellArg('raw value', 'bash');
309
+ expect(mockQuote).toHaveBeenCalledWith(['raw value']);
310
+ expect(result).toBe("'escaped value'");
311
+ });
312
+
313
+ it('should handle empty strings', () => {
314
+ const result = escapeShellArg('', 'bash');
315
+ expect(result).toBe('');
316
+ expect(mockQuote).not.toHaveBeenCalled();
317
+ });
318
+ });
319
+
320
+ describe('Windows', () => {
321
+ describe('when shell is cmd.exe', () => {
322
+ it('should wrap simple arguments in double quotes', () => {
323
+ const result = escapeShellArg('search term', 'cmd');
324
+ expect(result).toBe('"search term"');
325
+ });
326
+
327
+ it('should escape internal double quotes by doubling them', () => {
328
+ const result = escapeShellArg('He said "Hello"', 'cmd');
329
+ expect(result).toBe('"He said ""Hello"""');
330
+ });
331
+
332
+ it('should handle empty strings', () => {
333
+ const result = escapeShellArg('', 'cmd');
334
+ expect(result).toBe('');
335
+ });
336
+ });
337
+
338
+ describe('when shell is PowerShell', () => {
339
+ it('should wrap simple arguments in single quotes', () => {
340
+ const result = escapeShellArg('search term', 'powershell');
341
+ expect(result).toBe("'search term'");
342
+ });
343
+
344
+ it('should escape internal single quotes by doubling them', () => {
345
+ const result = escapeShellArg("It's a test", 'powershell');
346
+ expect(result).toBe("'It''s a test'");
347
+ });
348
+
349
+ it('should handle double quotes without escaping them', () => {
350
+ const result = escapeShellArg('He said "Hello"', 'powershell');
351
+ expect(result).toBe('\'He said "Hello"\'');
352
+ });
353
+
354
+ it('should handle empty strings', () => {
355
+ const result = escapeShellArg('', 'powershell');
356
+ expect(result).toBe('');
357
+ });
358
+ });
359
+ });
360
+ });
361
+
362
+ describe('getShellConfiguration', () => {
363
+ const originalEnv = { ...process.env };
364
+
365
+ afterEach(() => {
366
+ process.env = originalEnv;
367
+ });
368
+
369
+ it('should return bash configuration on Linux', () => {
370
+ mockPlatform.mockReturnValue('linux');
371
+ const config = getShellConfiguration();
372
+ expect(config.executable).toBe('bash');
373
+ expect(config.argsPrefix).toEqual(['-c']);
374
+ expect(config.shell).toBe('bash');
375
+ });
376
+
377
+ it('should return bash configuration on macOS (darwin)', () => {
378
+ mockPlatform.mockReturnValue('darwin');
379
+ const config = getShellConfiguration();
380
+ expect(config.executable).toBe('bash');
381
+ expect(config.argsPrefix).toEqual(['-c']);
382
+ expect(config.shell).toBe('bash');
383
+ });
384
+
385
+ describe('on Windows', () => {
386
+ beforeEach(() => {
387
+ mockPlatform.mockReturnValue('win32');
388
+ });
389
+
390
+ it('should return cmd.exe configuration by default', () => {
391
+ delete process.env['ComSpec'];
392
+ const config = getShellConfiguration();
393
+ expect(config.executable).toBe('cmd.exe');
394
+ expect(config.argsPrefix).toEqual(['/d', '/s', '/c']);
395
+ expect(config.shell).toBe('cmd');
396
+ });
397
+
398
+ it('should respect ComSpec for cmd.exe', () => {
399
+ const cmdPath = 'C:\\WINDOWS\\system32\\cmd.exe';
400
+ process.env['ComSpec'] = cmdPath;
401
+ const config = getShellConfiguration();
402
+ expect(config.executable).toBe(cmdPath);
403
+ expect(config.argsPrefix).toEqual(['/d', '/s', '/c']);
404
+ expect(config.shell).toBe('cmd');
405
+ });
406
+
407
+ it('should return PowerShell configuration if ComSpec points to powershell.exe', () => {
408
+ const psPath =
409
+ 'C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe';
410
+ process.env['ComSpec'] = psPath;
411
+ const config = getShellConfiguration();
412
+ expect(config.executable).toBe(psPath);
413
+ expect(config.argsPrefix).toEqual(['-NoProfile', '-Command']);
414
+ expect(config.shell).toBe('powershell');
415
+ });
416
+
417
+ it('should return PowerShell configuration if ComSpec points to pwsh.exe', () => {
418
+ const pwshPath = 'C:\\Program Files\\PowerShell\\7\\pwsh.exe';
419
+ process.env['ComSpec'] = pwshPath;
420
+ const config = getShellConfiguration();
421
+ expect(config.executable).toBe(pwshPath);
422
+ expect(config.argsPrefix).toEqual(['-NoProfile', '-Command']);
423
+ expect(config.shell).toBe('powershell');
424
+ });
425
+
426
+ it('should be case-insensitive when checking ComSpec', () => {
427
+ process.env['ComSpec'] = 'C:\\Path\\To\\POWERSHELL.EXE';
428
+ const config = getShellConfiguration();
429
+ expect(config.executable).toBe('C:\\Path\\To\\POWERSHELL.EXE');
430
+ expect(config.argsPrefix).toEqual(['-NoProfile', '-Command']);
431
+ expect(config.shell).toBe('powershell');
432
+ });
433
+ });
434
+ });
projects/ui/qwen-code/packages/core/src/utils/shell-utils.ts ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Config } from '../config/config.js';
8
+ import os from 'os';
9
+ import { quote } from 'shell-quote';
10
+
11
+ /**
12
+ * An identifier for the shell type.
13
+ */
14
+ export type ShellType = 'cmd' | 'powershell' | 'bash';
15
+
16
+ /**
17
+ * Defines the configuration required to execute a command string within a specific shell.
18
+ */
19
+ export interface ShellConfiguration {
20
+ /** The path or name of the shell executable (e.g., 'bash', 'cmd.exe'). */
21
+ executable: string;
22
+ /**
23
+ * The arguments required by the shell to execute a subsequent string argument.
24
+ */
25
+ argsPrefix: string[];
26
+ /** An identifier for the shell type. */
27
+ shell: ShellType;
28
+ }
29
+
30
+ /**
31
+ * Determines the appropriate shell configuration for the current platform.
32
+ *
33
+ * This ensures we can execute command strings predictably and securely across platforms
34
+ * using the `spawn(executable, [...argsPrefix, commandString], { shell: false })` pattern.
35
+ *
36
+ * @returns The ShellConfiguration for the current environment.
37
+ */
38
+ export function getShellConfiguration(): ShellConfiguration {
39
+ if (isWindows()) {
40
+ const comSpec = process.env['ComSpec'] || 'cmd.exe';
41
+ const executable = comSpec.toLowerCase();
42
+
43
+ if (
44
+ executable.endsWith('powershell.exe') ||
45
+ executable.endsWith('pwsh.exe')
46
+ ) {
47
+ // For PowerShell, the arguments are different.
48
+ // -NoProfile: Speeds up startup.
49
+ // -Command: Executes the following command.
50
+ return {
51
+ executable: comSpec,
52
+ argsPrefix: ['-NoProfile', '-Command'],
53
+ shell: 'powershell',
54
+ };
55
+ }
56
+
57
+ // Default to cmd.exe for anything else on Windows.
58
+ // Flags for CMD:
59
+ // /d: Skip execution of AutoRun commands.
60
+ // /s: Modifies the treatment of the command string (important for quoting).
61
+ // /c: Carries out the command specified by the string and then terminates.
62
+ return {
63
+ executable: comSpec,
64
+ argsPrefix: ['/d', '/s', '/c'],
65
+ shell: 'cmd',
66
+ };
67
+ }
68
+
69
+ // Unix-like systems (Linux, macOS)
70
+ return { executable: 'bash', argsPrefix: ['-c'], shell: 'bash' };
71
+ }
72
+
73
+ /**
74
+ * Export the platform detection constant for use in process management (e.g., killing processes).
75
+ */
76
+ export const isWindows = () => os.platform() === 'win32';
77
+
78
+ /**
79
+ * Escapes a string so that it can be safely used as a single argument
80
+ * in a shell command, preventing command injection.
81
+ *
82
+ * @param arg The argument string to escape.
83
+ * @param shell The type of shell the argument is for.
84
+ * @returns The shell-escaped string.
85
+ */
86
+ export function escapeShellArg(arg: string, shell: ShellType): string {
87
+ if (!arg) {
88
+ return '';
89
+ }
90
+
91
+ switch (shell) {
92
+ case 'powershell':
93
+ // For PowerShell, wrap in single quotes and escape internal single quotes by doubling them.
94
+ return `'${arg.replace(/'/g, "''")}'`;
95
+ case 'cmd':
96
+ // Simple Windows escaping for cmd.exe: wrap in double quotes and escape inner double quotes.
97
+ return `"${arg.replace(/"/g, '""')}"`;
98
+ case 'bash':
99
+ default:
100
+ // POSIX shell escaping using shell-quote.
101
+ return quote([arg]);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Splits a shell command into a list of individual commands, respecting quotes.
107
+ * This is used to separate chained commands (e.g., using &&, ||, ;).
108
+ * @param command The shell command string to parse
109
+ * @returns An array of individual command strings
110
+ */
111
+ export function splitCommands(command: string): string[] {
112
+ const commands: string[] = [];
113
+ let currentCommand = '';
114
+ let inSingleQuotes = false;
115
+ let inDoubleQuotes = false;
116
+ let i = 0;
117
+
118
+ while (i < command.length) {
119
+ const char = command[i];
120
+ const nextChar = command[i + 1];
121
+
122
+ if (char === '\\' && i < command.length - 1) {
123
+ currentCommand += char + command[i + 1];
124
+ i += 2;
125
+ continue;
126
+ }
127
+
128
+ if (char === "'" && !inDoubleQuotes) {
129
+ inSingleQuotes = !inSingleQuotes;
130
+ } else if (char === '"' && !inSingleQuotes) {
131
+ inDoubleQuotes = !inDoubleQuotes;
132
+ }
133
+
134
+ if (!inSingleQuotes && !inDoubleQuotes) {
135
+ if (
136
+ (char === '&' && nextChar === '&') ||
137
+ (char === '|' && nextChar === '|')
138
+ ) {
139
+ commands.push(currentCommand.trim());
140
+ currentCommand = '';
141
+ i++; // Skip the next character
142
+ } else if (char === ';' || char === '&' || char === '|') {
143
+ commands.push(currentCommand.trim());
144
+ currentCommand = '';
145
+ } else {
146
+ currentCommand += char;
147
+ }
148
+ } else {
149
+ currentCommand += char;
150
+ }
151
+ i++;
152
+ }
153
+
154
+ if (currentCommand.trim()) {
155
+ commands.push(currentCommand.trim());
156
+ }
157
+
158
+ return commands.filter(Boolean); // Filter out any empty strings
159
+ }
160
+
161
+ /**
162
+ * Extracts the root command from a given shell command string.
163
+ * This is used to identify the base command for permission checks.
164
+ * @param command The shell command string to parse
165
+ * @returns The root command name, or undefined if it cannot be determined
166
+ * @example getCommandRoot("ls -la /tmp") returns "ls"
167
+ * @example getCommandRoot("git status && npm test") returns "git"
168
+ */
169
+ export function getCommandRoot(command: string): string | undefined {
170
+ const trimmedCommand = command.trim();
171
+ if (!trimmedCommand) {
172
+ return undefined;
173
+ }
174
+
175
+ // This regex is designed to find the first "word" of a command,
176
+ // while respecting quotes. It looks for a sequence of non-whitespace
177
+ // characters that are not inside quotes.
178
+ const match = trimmedCommand.match(/^"([^"]+)"|^'([^']+)'|^(\S+)/);
179
+ if (match) {
180
+ // The first element in the match array is the full match.
181
+ // The subsequent elements are the capture groups.
182
+ // We prefer a captured group because it will be unquoted.
183
+ const commandRoot = match[1] || match[2] || match[3];
184
+ if (commandRoot) {
185
+ // If the command is a path, return the last component.
186
+ return commandRoot.split(/[\\/]/).pop();
187
+ }
188
+ }
189
+
190
+ return undefined;
191
+ }
192
+
193
+ export function getCommandRoots(command: string): string[] {
194
+ if (!command) {
195
+ return [];
196
+ }
197
+ return splitCommands(command)
198
+ .map((c) => getCommandRoot(c))
199
+ .filter((c): c is string => !!c);
200
+ }
201
+
202
+ export function stripShellWrapper(command: string): string {
203
+ const pattern = /^\s*(?:sh|bash|zsh|cmd.exe)\s+(?:\/c|-c)\s+/;
204
+ const match = command.match(pattern);
205
+ if (match) {
206
+ let newCommand = command.substring(match[0].length).trim();
207
+ if (
208
+ (newCommand.startsWith('"') && newCommand.endsWith('"')) ||
209
+ (newCommand.startsWith("'") && newCommand.endsWith("'"))
210
+ ) {
211
+ newCommand = newCommand.substring(1, newCommand.length - 1);
212
+ }
213
+ return newCommand;
214
+ }
215
+ return command.trim();
216
+ }
217
+
218
+ /**
219
+ * Detects command substitution patterns in a shell command, following bash quoting rules:
220
+ * - Single quotes ('): Everything literal, no substitution possible
221
+ * - Double quotes ("): Command substitution with $() and backticks unless escaped with \
222
+ * - No quotes: Command substitution with $(), <(), and backticks
223
+ * @param command The shell command string to check
224
+ * @returns true if command substitution would be executed by bash
225
+ */
226
+ export function detectCommandSubstitution(command: string): boolean {
227
+ let inSingleQuotes = false;
228
+ let inDoubleQuotes = false;
229
+ let inBackticks = false;
230
+ let i = 0;
231
+
232
+ while (i < command.length) {
233
+ const char = command[i];
234
+ const nextChar = command[i + 1];
235
+
236
+ // Handle escaping - only works outside single quotes
237
+ if (char === '\\' && !inSingleQuotes) {
238
+ i += 2; // Skip the escaped character
239
+ continue;
240
+ }
241
+
242
+ // Handle quote state changes
243
+ if (char === "'" && !inDoubleQuotes && !inBackticks) {
244
+ inSingleQuotes = !inSingleQuotes;
245
+ } else if (char === '"' && !inSingleQuotes && !inBackticks) {
246
+ inDoubleQuotes = !inDoubleQuotes;
247
+ } else if (char === '`' && !inSingleQuotes) {
248
+ // Backticks work outside single quotes (including in double quotes)
249
+ inBackticks = !inBackticks;
250
+ }
251
+
252
+ // Check for command substitution patterns that would be executed
253
+ if (!inSingleQuotes) {
254
+ // $(...) command substitution - works in double quotes and unquoted
255
+ if (char === '$' && nextChar === '(') {
256
+ return true;
257
+ }
258
+
259
+ // <(...) process substitution - works unquoted only (not in double quotes)
260
+ if (char === '<' && nextChar === '(' && !inDoubleQuotes && !inBackticks) {
261
+ return true;
262
+ }
263
+
264
+ // Backtick command substitution - check for opening backtick
265
+ // (We track the state above, so this catches the start of backtick substitution)
266
+ if (char === '`' && !inBackticks) {
267
+ return true;
268
+ }
269
+ }
270
+
271
+ i++;
272
+ }
273
+
274
+ return false;
275
+ }
276
+
277
+ /**
278
+ * Checks a shell command against security policies and allowlists.
279
+ *
280
+ * This function operates in one of two modes depending on the presence of
281
+ * the `sessionAllowlist` parameter:
282
+ *
283
+ * 1. **"Default Deny" Mode (sessionAllowlist is provided):** This is the
284
+ * strictest mode, used for user-defined scripts like custom commands.
285
+ * A command is only permitted if it is found on the global `coreTools`
286
+ * allowlist OR the provided `sessionAllowlist`. It must not be on the
287
+ * global `excludeTools` blocklist.
288
+ *
289
+ * 2. **"Default Allow" Mode (sessionAllowlist is NOT provided):** This mode
290
+ * is used for direct tool invocations (e.g., by the model). If a strict
291
+ * global `coreTools` allowlist exists, commands must be on it. Otherwise,
292
+ * any command is permitted as long as it is not on the `excludeTools`
293
+ * blocklist.
294
+ *
295
+ * @param command The shell command string to validate.
296
+ * @param config The application configuration.
297
+ * @param sessionAllowlist A session-level list of approved commands. Its
298
+ * presence activates "Default Deny" mode.
299
+ * @returns An object detailing which commands are not allowed.
300
+ */
301
+ export function checkCommandPermissions(
302
+ command: string,
303
+ config: Config,
304
+ sessionAllowlist?: Set<string>,
305
+ ): {
306
+ allAllowed: boolean;
307
+ disallowedCommands: string[];
308
+ blockReason?: string;
309
+ isHardDenial?: boolean;
310
+ } {
311
+ // Disallow command substitution for security.
312
+ if (detectCommandSubstitution(command)) {
313
+ return {
314
+ allAllowed: false,
315
+ disallowedCommands: [command],
316
+ blockReason:
317
+ 'Command substitution using $(), <(), or >() is not allowed for security reasons',
318
+ isHardDenial: true,
319
+ };
320
+ }
321
+
322
+ const SHELL_TOOL_NAMES = ['run_shell_command', 'ShellTool'];
323
+ const normalize = (cmd: string): string => cmd.trim().replace(/\s+/g, ' ');
324
+
325
+ const isPrefixedBy = (cmd: string, prefix: string): boolean => {
326
+ if (!cmd.startsWith(prefix)) {
327
+ return false;
328
+ }
329
+ return cmd.length === prefix.length || cmd[prefix.length] === ' ';
330
+ };
331
+
332
+ const extractCommands = (tools: string[]): string[] =>
333
+ tools.flatMap((tool) => {
334
+ for (const toolName of SHELL_TOOL_NAMES) {
335
+ if (tool.startsWith(`${toolName}(`) && tool.endsWith(')')) {
336
+ return [normalize(tool.slice(toolName.length + 1, -1))];
337
+ }
338
+ }
339
+ return [];
340
+ });
341
+
342
+ const coreTools = config.getCoreTools() || [];
343
+ const excludeTools = config.getExcludeTools() || [];
344
+ const commandsToValidate = splitCommands(command).map(normalize);
345
+
346
+ // 1. Blocklist Check (Highest Priority)
347
+ if (SHELL_TOOL_NAMES.some((name) => excludeTools.includes(name))) {
348
+ return {
349
+ allAllowed: false,
350
+ disallowedCommands: commandsToValidate,
351
+ blockReason: 'Shell tool is globally disabled in configuration',
352
+ isHardDenial: true,
353
+ };
354
+ }
355
+ const blockedCommands = extractCommands(excludeTools);
356
+ for (const cmd of commandsToValidate) {
357
+ if (blockedCommands.some((blocked) => isPrefixedBy(cmd, blocked))) {
358
+ return {
359
+ allAllowed: false,
360
+ disallowedCommands: [cmd],
361
+ blockReason: `Command '${cmd}' is blocked by configuration`,
362
+ isHardDenial: true,
363
+ };
364
+ }
365
+ }
366
+
367
+ const globallyAllowedCommands = extractCommands(coreTools);
368
+ const isWildcardAllowed = SHELL_TOOL_NAMES.some((name) =>
369
+ coreTools.includes(name),
370
+ );
371
+
372
+ // If there's a global wildcard, all commands are allowed at this point
373
+ // because they have already passed the blocklist check.
374
+ if (isWildcardAllowed) {
375
+ return { allAllowed: true, disallowedCommands: [] };
376
+ }
377
+
378
+ if (sessionAllowlist) {
379
+ // "DEFAULT DENY" MODE: A session allowlist is provided.
380
+ // All commands must be in either the session or global allowlist.
381
+ const disallowedCommands: string[] = [];
382
+ for (const cmd of commandsToValidate) {
383
+ const isSessionAllowed = [...sessionAllowlist].some((allowed) =>
384
+ isPrefixedBy(cmd, normalize(allowed)),
385
+ );
386
+ if (isSessionAllowed) continue;
387
+
388
+ const isGloballyAllowed = globallyAllowedCommands.some((allowed) =>
389
+ isPrefixedBy(cmd, allowed),
390
+ );
391
+ if (isGloballyAllowed) continue;
392
+
393
+ disallowedCommands.push(cmd);
394
+ }
395
+
396
+ if (disallowedCommands.length > 0) {
397
+ return {
398
+ allAllowed: false,
399
+ disallowedCommands,
400
+ blockReason: `Command(s) not on the global or session allowlist. Disallowed commands: ${disallowedCommands
401
+ .map((c) => JSON.stringify(c))
402
+ .join(', ')}`,
403
+ isHardDenial: false, // This is a soft denial; confirmation is possible.
404
+ };
405
+ }
406
+ } else {
407
+ // "DEFAULT ALLOW" MODE: No session allowlist.
408
+ const hasSpecificAllowedCommands = globallyAllowedCommands.length > 0;
409
+ if (hasSpecificAllowedCommands) {
410
+ const disallowedCommands: string[] = [];
411
+ for (const cmd of commandsToValidate) {
412
+ const isGloballyAllowed = globallyAllowedCommands.some((allowed) =>
413
+ isPrefixedBy(cmd, allowed),
414
+ );
415
+ if (!isGloballyAllowed) {
416
+ disallowedCommands.push(cmd);
417
+ }
418
+ }
419
+ if (disallowedCommands.length > 0) {
420
+ return {
421
+ allAllowed: false,
422
+ disallowedCommands,
423
+ blockReason: `Command(s) not in the allowed commands list. Disallowed commands: ${disallowedCommands.map((c) => JSON.stringify(c)).join(', ')}`,
424
+ isHardDenial: false, // This is a soft denial.
425
+ };
426
+ }
427
+ }
428
+ // If no specific global allowlist exists, and it passed the blocklist,
429
+ // the command is allowed by default.
430
+ }
431
+
432
+ // If all checks for the current mode pass, the command is allowed.
433
+ return { allAllowed: true, disallowedCommands: [] };
434
+ }
435
+
436
+ /**
437
+ * Determines whether a given shell command is allowed to execute based on
438
+ * the tool's configuration including allowlists and blocklists.
439
+ *
440
+ * This function operates in "default allow" mode. It is a wrapper around
441
+ * `checkCommandPermissions`.
442
+ *
443
+ * @param command The shell command string to validate.
444
+ * @param config The application configuration.
445
+ * @returns An object with 'allowed' boolean and optional 'reason' string if not allowed.
446
+ */
447
+ export function isCommandAllowed(
448
+ command: string,
449
+ config: Config,
450
+ ): { allowed: boolean; reason?: string } {
451
+ // By not providing a sessionAllowlist, we invoke "default allow" behavior.
452
+ const { allAllowed, blockReason } = checkCommandPermissions(command, config);
453
+ if (allAllowed) {
454
+ return { allowed: true };
455
+ }
456
+ return { allowed: false, reason: blockReason };
457
+ }
projects/ui/qwen-code/packages/core/src/utils/summarizer.test.ts ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Mock } from 'vitest';
8
+ import { GeminiClient } from '../core/client.js';
9
+ import { Config } from '../config/config.js';
10
+ import {
11
+ summarizeToolOutput,
12
+ llmSummarizer,
13
+ defaultSummarizer,
14
+ } from './summarizer.js';
15
+ import { ToolResult } from '../tools/tools.js';
16
+
17
+ // Mock GeminiClient and Config constructor
18
+ vi.mock('../core/client.js');
19
+ vi.mock('../config/config.js');
20
+
21
+ describe('summarizers', () => {
22
+ let mockGeminiClient: GeminiClient;
23
+ let MockConfig: Mock;
24
+ const abortSignal = new AbortController().signal;
25
+
26
+ beforeEach(() => {
27
+ MockConfig = vi.mocked(Config);
28
+ const mockConfigInstance = new MockConfig(
29
+ 'test-api-key',
30
+ 'gemini-pro',
31
+ false,
32
+ '.',
33
+ false,
34
+ undefined,
35
+ false,
36
+ undefined,
37
+ undefined,
38
+ undefined,
39
+ );
40
+
41
+ mockGeminiClient = new GeminiClient(mockConfigInstance);
42
+ (mockGeminiClient.generateContent as Mock) = vi.fn();
43
+
44
+ vi.spyOn(console, 'error').mockImplementation(() => {});
45
+ });
46
+
47
+ afterEach(() => {
48
+ vi.clearAllMocks();
49
+ (console.error as Mock).mockRestore();
50
+ });
51
+
52
+ describe('summarizeToolOutput', () => {
53
+ it('should return original text if it is shorter than maxLength', async () => {
54
+ const shortText = 'This is a short text.';
55
+ const result = await summarizeToolOutput(
56
+ shortText,
57
+ mockGeminiClient,
58
+ abortSignal,
59
+ 2000,
60
+ );
61
+ expect(result).toBe(shortText);
62
+ expect(mockGeminiClient.generateContent).not.toHaveBeenCalled();
63
+ });
64
+
65
+ it('should return original text if it is empty', async () => {
66
+ const emptyText = '';
67
+ const result = await summarizeToolOutput(
68
+ emptyText,
69
+ mockGeminiClient,
70
+ abortSignal,
71
+ 2000,
72
+ );
73
+ expect(result).toBe(emptyText);
74
+ expect(mockGeminiClient.generateContent).not.toHaveBeenCalled();
75
+ });
76
+
77
+ it('should call generateContent if text is longer than maxLength', async () => {
78
+ const longText = 'This is a very long text.'.repeat(200);
79
+ const summary = 'This is a summary.';
80
+ (mockGeminiClient.generateContent as Mock).mockResolvedValue({
81
+ candidates: [{ content: { parts: [{ text: summary }] } }],
82
+ });
83
+
84
+ const result = await summarizeToolOutput(
85
+ longText,
86
+ mockGeminiClient,
87
+ abortSignal,
88
+ 2000,
89
+ );
90
+
91
+ expect(mockGeminiClient.generateContent).toHaveBeenCalledTimes(1);
92
+ expect(result).toBe(summary);
93
+ });
94
+
95
+ it('should return original text if generateContent throws an error', async () => {
96
+ const longText = 'This is a very long text.'.repeat(200);
97
+ const error = new Error('API Error');
98
+ (mockGeminiClient.generateContent as Mock).mockRejectedValue(error);
99
+
100
+ const result = await summarizeToolOutput(
101
+ longText,
102
+ mockGeminiClient,
103
+ abortSignal,
104
+ 2000,
105
+ );
106
+
107
+ expect(mockGeminiClient.generateContent).toHaveBeenCalledTimes(1);
108
+ expect(result).toBe(longText);
109
+ expect(console.error).toHaveBeenCalledWith(
110
+ 'Failed to summarize tool output.',
111
+ error,
112
+ );
113
+ });
114
+
115
+ it('should construct the correct prompt for summarization', async () => {
116
+ const longText = 'This is a very long text.'.repeat(200);
117
+ const summary = 'This is a summary.';
118
+ (mockGeminiClient.generateContent as Mock).mockResolvedValue({
119
+ candidates: [{ content: { parts: [{ text: summary }] } }],
120
+ });
121
+
122
+ await summarizeToolOutput(longText, mockGeminiClient, abortSignal, 1000);
123
+
124
+ const expectedPrompt = `Summarize the following tool output to be a maximum of 1000 tokens. The summary should be concise and capture the main points of the tool output.
125
+
126
+ The summarization should be done based on the content that is provided. Here are the basic rules to follow:
127
+ 1. If the text is a directory listing or any output that is structural, use the history of the conversation to understand the context. Using this context try to understand what information we need from the tool output and return that as a response.
128
+ 2. If the text is text content and there is nothing structural that we need, summarize the text.
129
+ 3. If the text is the output of a shell command, use the history of the conversation to understand the context. Using this context try to understand what information we need from the tool output and return a summarization along with the stack trace of any error within the <error></error> tags. The stack trace should be complete and not truncated. If there are warnings, you should include them in the summary within <warning></warning> tags.
130
+
131
+
132
+ Text to summarize:
133
+ "${longText}"
134
+
135
+ Return the summary string which should first contain an overall summarization of text followed by the full stack trace of errors and warnings in the tool output.
136
+ `;
137
+ const calledWith = (mockGeminiClient.generateContent as Mock).mock
138
+ .calls[0];
139
+ const contents = calledWith[0];
140
+ expect(contents[0].parts[0].text).toBe(expectedPrompt);
141
+ });
142
+ });
143
+
144
+ describe('llmSummarizer', () => {
145
+ it('should summarize tool output using summarizeToolOutput', async () => {
146
+ const toolResult: ToolResult = {
147
+ llmContent: 'This is a very long text.'.repeat(200),
148
+ returnDisplay: '',
149
+ };
150
+ const summary = 'This is a summary.';
151
+ (mockGeminiClient.generateContent as Mock).mockResolvedValue({
152
+ candidates: [{ content: { parts: [{ text: summary }] } }],
153
+ });
154
+
155
+ const result = await llmSummarizer(
156
+ toolResult,
157
+ mockGeminiClient,
158
+ abortSignal,
159
+ );
160
+
161
+ expect(mockGeminiClient.generateContent).toHaveBeenCalledTimes(1);
162
+ expect(result).toBe(summary);
163
+ });
164
+
165
+ it('should handle different llmContent types', async () => {
166
+ const longText = 'This is a very long text.'.repeat(200);
167
+ const toolResult: ToolResult = {
168
+ llmContent: [{ text: longText }],
169
+ returnDisplay: '',
170
+ };
171
+ const summary = 'This is a summary.';
172
+ (mockGeminiClient.generateContent as Mock).mockResolvedValue({
173
+ candidates: [{ content: { parts: [{ text: summary }] } }],
174
+ });
175
+
176
+ const result = await llmSummarizer(
177
+ toolResult,
178
+ mockGeminiClient,
179
+ abortSignal,
180
+ );
181
+
182
+ expect(mockGeminiClient.generateContent).toHaveBeenCalledTimes(1);
183
+ const calledWith = (mockGeminiClient.generateContent as Mock).mock
184
+ .calls[0];
185
+ const contents = calledWith[0];
186
+ expect(contents[0].parts[0].text).toContain(`"${longText}"`);
187
+ expect(result).toBe(summary);
188
+ });
189
+ });
190
+
191
+ describe('defaultSummarizer', () => {
192
+ it('should stringify the llmContent', async () => {
193
+ const toolResult: ToolResult = {
194
+ llmContent: { text: 'some data' },
195
+ returnDisplay: '',
196
+ };
197
+
198
+ const result = await defaultSummarizer(
199
+ toolResult,
200
+ mockGeminiClient,
201
+ abortSignal,
202
+ );
203
+
204
+ expect(result).toBe(JSON.stringify({ text: 'some data' }));
205
+ expect(mockGeminiClient.generateContent).not.toHaveBeenCalled();
206
+ });
207
+ });
208
+ });
projects/ui/qwen-code/packages/core/src/utils/summarizer.ts ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { ToolResult } from '../tools/tools.js';
8
+ import {
9
+ Content,
10
+ GenerateContentConfig,
11
+ GenerateContentResponse,
12
+ } from '@google/genai';
13
+ import { GeminiClient } from '../core/client.js';
14
+ import { DEFAULT_GEMINI_FLASH_LITE_MODEL } from '../config/models.js';
15
+ import { getResponseText, partToString } from './partUtils.js';
16
+
17
+ /**
18
+ * A function that summarizes the result of a tool execution.
19
+ *
20
+ * @param result The result of the tool execution.
21
+ * @returns The summary of the result.
22
+ */
23
+ export type Summarizer = (
24
+ result: ToolResult,
25
+ geminiClient: GeminiClient,
26
+ abortSignal: AbortSignal,
27
+ ) => Promise<string>;
28
+
29
+ /**
30
+ * The default summarizer for tool results.
31
+ *
32
+ * @param result The result of the tool execution.
33
+ * @param geminiClient The Gemini client to use for summarization.
34
+ * @param abortSignal The abort signal to use for summarization.
35
+ * @returns The summary of the result.
36
+ */
37
+ export const defaultSummarizer: Summarizer = (
38
+ result: ToolResult,
39
+ _geminiClient: GeminiClient,
40
+ _abortSignal: AbortSignal,
41
+ ) => Promise.resolve(JSON.stringify(result.llmContent));
42
+
43
+ const SUMMARIZE_TOOL_OUTPUT_PROMPT = `Summarize the following tool output to be a maximum of {maxOutputTokens} tokens. The summary should be concise and capture the main points of the tool output.
44
+
45
+ The summarization should be done based on the content that is provided. Here are the basic rules to follow:
46
+ 1. If the text is a directory listing or any output that is structural, use the history of the conversation to understand the context. Using this context try to understand what information we need from the tool output and return that as a response.
47
+ 2. If the text is text content and there is nothing structural that we need, summarize the text.
48
+ 3. If the text is the output of a shell command, use the history of the conversation to understand the context. Using this context try to understand what information we need from the tool output and return a summarization along with the stack trace of any error within the <error></error> tags. The stack trace should be complete and not truncated. If there are warnings, you should include them in the summary within <warning></warning> tags.
49
+
50
+
51
+ Text to summarize:
52
+ "{textToSummarize}"
53
+
54
+ Return the summary string which should first contain an overall summarization of text followed by the full stack trace of errors and warnings in the tool output.
55
+ `;
56
+
57
+ export const llmSummarizer: Summarizer = (result, geminiClient, abortSignal) =>
58
+ summarizeToolOutput(
59
+ partToString(result.llmContent),
60
+ geminiClient,
61
+ abortSignal,
62
+ );
63
+
64
+ export async function summarizeToolOutput(
65
+ textToSummarize: string,
66
+ geminiClient: GeminiClient,
67
+ abortSignal: AbortSignal,
68
+ maxOutputTokens: number = 2000,
69
+ ): Promise<string> {
70
+ // There is going to be a slight difference here since we are comparing length of string with maxOutputTokens.
71
+ // This is meant to be a ballpark estimation of if we need to summarize the tool output.
72
+ if (!textToSummarize || textToSummarize.length < maxOutputTokens) {
73
+ return textToSummarize;
74
+ }
75
+ const prompt = SUMMARIZE_TOOL_OUTPUT_PROMPT.replace(
76
+ '{maxOutputTokens}',
77
+ String(maxOutputTokens),
78
+ ).replace('{textToSummarize}', textToSummarize);
79
+
80
+ const contents: Content[] = [{ role: 'user', parts: [{ text: prompt }] }];
81
+ const toolOutputSummarizerConfig: GenerateContentConfig = {
82
+ maxOutputTokens,
83
+ };
84
+ try {
85
+ const parsedResponse = (await geminiClient.generateContent(
86
+ contents,
87
+ toolOutputSummarizerConfig,
88
+ abortSignal,
89
+ DEFAULT_GEMINI_FLASH_LITE_MODEL,
90
+ )) as unknown as GenerateContentResponse;
91
+ return getResponseText(parsedResponse) || textToSummarize;
92
+ } catch (error) {
93
+ console.error('Failed to summarize tool output.', error);
94
+ return textToSummarize;
95
+ }
96
+ }
projects/ui/qwen-code/packages/core/src/utils/systemEncoding.test.ts ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { execSync } from 'child_process';
9
+ import * as os from 'os';
10
+ import { detect as chardetDetect } from 'chardet';
11
+
12
+ // Mock dependencies
13
+ vi.mock('child_process');
14
+ vi.mock('os');
15
+ vi.mock('chardet');
16
+
17
+ // Import the functions we want to test after refactoring
18
+ import {
19
+ getCachedEncodingForBuffer,
20
+ getSystemEncoding,
21
+ windowsCodePageToEncoding,
22
+ detectEncodingFromBuffer,
23
+ resetEncodingCache,
24
+ } from './systemEncoding.js';
25
+
26
+ describe('Shell Command Processor - Encoding Functions', () => {
27
+ let consoleWarnSpy: ReturnType<typeof vi.spyOn>;
28
+ let mockedExecSync: ReturnType<typeof vi.mocked<typeof execSync>>;
29
+ let mockedOsPlatform: ReturnType<typeof vi.mocked<() => string>>;
30
+ let mockedChardetDetect: ReturnType<typeof vi.mocked<typeof chardetDetect>>;
31
+
32
+ beforeEach(() => {
33
+ consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
34
+ mockedExecSync = vi.mocked(execSync);
35
+ mockedOsPlatform = vi.mocked(os.platform);
36
+ mockedChardetDetect = vi.mocked(chardetDetect);
37
+
38
+ // Reset the encoding cache before each test
39
+ resetEncodingCache();
40
+
41
+ // Clear environment variables that might affect tests
42
+ delete process.env['LC_ALL'];
43
+ delete process.env['LC_CTYPE'];
44
+ delete process.env['LANG'];
45
+ });
46
+
47
+ afterEach(() => {
48
+ vi.restoreAllMocks();
49
+ resetEncodingCache();
50
+ });
51
+
52
+ describe('windowsCodePageToEncoding', () => {
53
+ it('should map common Windows code pages correctly', () => {
54
+ expect(windowsCodePageToEncoding(437)).toBe('cp437');
55
+ expect(windowsCodePageToEncoding(850)).toBe('cp850');
56
+ expect(windowsCodePageToEncoding(65001)).toBe('utf-8');
57
+ expect(windowsCodePageToEncoding(1252)).toBe('windows-1252');
58
+ expect(windowsCodePageToEncoding(932)).toBe('shift_jis');
59
+ expect(windowsCodePageToEncoding(936)).toBe('gb2312');
60
+ expect(windowsCodePageToEncoding(949)).toBe('euc-kr');
61
+ expect(windowsCodePageToEncoding(950)).toBe('big5');
62
+ expect(windowsCodePageToEncoding(1200)).toBe('utf-16le');
63
+ expect(windowsCodePageToEncoding(1201)).toBe('utf-16be');
64
+ });
65
+
66
+ it('should return null for unmapped code pages and warn', () => {
67
+ expect(windowsCodePageToEncoding(99999)).toBe(null);
68
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
69
+ 'Unable to determine encoding for windows code page 99999.',
70
+ );
71
+ });
72
+
73
+ it('should handle all Windows-specific code pages', () => {
74
+ expect(windowsCodePageToEncoding(874)).toBe('windows-874');
75
+ expect(windowsCodePageToEncoding(1250)).toBe('windows-1250');
76
+ expect(windowsCodePageToEncoding(1251)).toBe('windows-1251');
77
+ expect(windowsCodePageToEncoding(1253)).toBe('windows-1253');
78
+ expect(windowsCodePageToEncoding(1254)).toBe('windows-1254');
79
+ expect(windowsCodePageToEncoding(1255)).toBe('windows-1255');
80
+ expect(windowsCodePageToEncoding(1256)).toBe('windows-1256');
81
+ expect(windowsCodePageToEncoding(1257)).toBe('windows-1257');
82
+ expect(windowsCodePageToEncoding(1258)).toBe('windows-1258');
83
+ });
84
+ });
85
+
86
+ describe('detectEncodingFromBuffer', () => {
87
+ it('should detect encoding using chardet successfully', () => {
88
+ const buffer = Buffer.from('test content', 'utf8');
89
+ mockedChardetDetect.mockReturnValue('UTF-8');
90
+
91
+ const result = detectEncodingFromBuffer(buffer);
92
+ expect(result).toBe('utf-8');
93
+ expect(mockedChardetDetect).toHaveBeenCalledWith(buffer);
94
+ });
95
+
96
+ it('should handle chardet returning mixed case encoding', () => {
97
+ const buffer = Buffer.from('test content', 'utf8');
98
+ mockedChardetDetect.mockReturnValue('ISO-8859-1');
99
+
100
+ const result = detectEncodingFromBuffer(buffer);
101
+ expect(result).toBe('iso-8859-1');
102
+ });
103
+
104
+ it('should return null when chardet fails', () => {
105
+ const buffer = Buffer.from('test content', 'utf8');
106
+ mockedChardetDetect.mockImplementation(() => {
107
+ throw new Error('Detection failed');
108
+ });
109
+
110
+ const result = detectEncodingFromBuffer(buffer);
111
+ expect(result).toBe(null);
112
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
113
+ 'Failed to detect encoding with chardet:',
114
+ expect.any(Error),
115
+ );
116
+ });
117
+
118
+ it('should return null when chardet returns null', () => {
119
+ const buffer = Buffer.from('test content', 'utf8');
120
+ mockedChardetDetect.mockReturnValue(null);
121
+
122
+ const result = detectEncodingFromBuffer(buffer);
123
+ expect(result).toBe(null);
124
+ });
125
+
126
+ it('should return null when chardet returns non-string', () => {
127
+ const buffer = Buffer.from('test content', 'utf8');
128
+ mockedChardetDetect.mockReturnValue([
129
+ 'utf-8',
130
+ 'iso-8859-1',
131
+ ] as unknown as string);
132
+
133
+ const result = detectEncodingFromBuffer(buffer);
134
+ expect(result).toBe(null);
135
+ });
136
+ });
137
+
138
+ describe('getSystemEncoding - Windows', () => {
139
+ beforeEach(() => {
140
+ mockedOsPlatform.mockReturnValue('win32');
141
+ });
142
+
143
+ it('should parse Windows chcp output correctly', () => {
144
+ mockedExecSync.mockReturnValue('Active code page: 65001');
145
+
146
+ const result = getSystemEncoding();
147
+ expect(result).toBe('utf-8');
148
+ expect(mockedExecSync).toHaveBeenCalledWith('chcp', { encoding: 'utf8' });
149
+ });
150
+
151
+ it('should handle different chcp output formats', () => {
152
+ mockedExecSync.mockReturnValue('Current code page: 1252');
153
+
154
+ const result = getSystemEncoding();
155
+ expect(result).toBe('windows-1252');
156
+ });
157
+
158
+ it('should handle chcp output with extra whitespace', () => {
159
+ mockedExecSync.mockReturnValue('Active code page: 437 ');
160
+
161
+ const result = getSystemEncoding();
162
+ expect(result).toBe('cp437');
163
+ });
164
+
165
+ it('should return null when chcp command fails', () => {
166
+ mockedExecSync.mockImplementation(() => {
167
+ throw new Error('Command failed');
168
+ });
169
+
170
+ const result = getSystemEncoding();
171
+ expect(result).toBe(null);
172
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
173
+ expect.stringContaining(
174
+ "Failed to get Windows code page using 'chcp' command",
175
+ ),
176
+ );
177
+ });
178
+
179
+ it('should return null when chcp output cannot be parsed', () => {
180
+ mockedExecSync.mockReturnValue('Unexpected output format');
181
+
182
+ const result = getSystemEncoding();
183
+ expect(result).toBe(null);
184
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
185
+ expect.stringContaining(
186
+ "Failed to get Windows code page using 'chcp' command",
187
+ ),
188
+ );
189
+ });
190
+
191
+ it('should return null when code page is not a number', () => {
192
+ mockedExecSync.mockReturnValue('Active code page: abc');
193
+
194
+ const result = getSystemEncoding();
195
+ expect(result).toBe(null);
196
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
197
+ expect.stringContaining(
198
+ "Failed to get Windows code page using 'chcp' command",
199
+ ),
200
+ );
201
+ });
202
+
203
+ it('should return null when code page maps to null', () => {
204
+ mockedExecSync.mockReturnValue('Active code page: 99999');
205
+
206
+ const result = getSystemEncoding();
207
+ expect(result).toBe(null);
208
+ // Should warn about unknown code page from windowsCodePageToEncoding
209
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
210
+ 'Unable to determine encoding for windows code page 99999.',
211
+ );
212
+ });
213
+ });
214
+
215
+ describe('getSystemEncoding - Unix-like', () => {
216
+ beforeEach(() => {
217
+ mockedOsPlatform.mockReturnValue('linux');
218
+ });
219
+
220
+ it('should parse locale from LC_ALL environment variable', () => {
221
+ process.env['LC_ALL'] = 'en_US.UTF-8';
222
+
223
+ const result = getSystemEncoding();
224
+ expect(result).toBe('utf-8');
225
+ });
226
+
227
+ it('should parse locale from LC_CTYPE when LC_ALL is not set', () => {
228
+ process.env['LC_CTYPE'] = 'fr_FR.ISO-8859-1';
229
+
230
+ const result = getSystemEncoding();
231
+ expect(result).toBe('iso-8859-1');
232
+ });
233
+
234
+ it('should parse locale from LANG when LC_ALL and LC_CTYPE are not set', () => {
235
+ process.env['LANG'] = 'de_DE.UTF-8';
236
+
237
+ const result = getSystemEncoding();
238
+ expect(result).toBe('utf-8');
239
+ });
240
+
241
+ it('should handle locale charmap command when environment variables are empty', () => {
242
+ mockedExecSync.mockReturnValue('UTF-8\n');
243
+
244
+ const result = getSystemEncoding();
245
+ expect(result).toBe('utf-8');
246
+ expect(mockedExecSync).toHaveBeenCalledWith('locale charmap', {
247
+ encoding: 'utf8',
248
+ });
249
+ });
250
+
251
+ it('should handle locale charmap with mixed case', () => {
252
+ mockedExecSync.mockReturnValue('ISO-8859-1\n');
253
+
254
+ const result = getSystemEncoding();
255
+ expect(result).toBe('iso-8859-1');
256
+ });
257
+
258
+ it('should return null when locale charmap fails', () => {
259
+ mockedExecSync.mockImplementation(() => {
260
+ throw new Error('Command failed');
261
+ });
262
+
263
+ const result = getSystemEncoding();
264
+ expect(result).toBe(null);
265
+ expect(consoleWarnSpy).toHaveBeenCalledWith(
266
+ 'Failed to get locale charmap.',
267
+ );
268
+ });
269
+
270
+ it('should handle locale without encoding (no dot)', () => {
271
+ process.env['LANG'] = 'C';
272
+
273
+ const result = getSystemEncoding();
274
+ expect(result).toBe('c');
275
+ });
276
+
277
+ it('should handle empty locale environment variables', () => {
278
+ process.env['LC_ALL'] = '';
279
+ process.env['LC_CTYPE'] = '';
280
+ process.env['LANG'] = '';
281
+ mockedExecSync.mockReturnValue('UTF-8');
282
+
283
+ const result = getSystemEncoding();
284
+ expect(result).toBe('utf-8');
285
+ });
286
+
287
+ it('should return locale as-is when locale format has no dot', () => {
288
+ process.env['LANG'] = 'invalid_format';
289
+
290
+ const result = getSystemEncoding();
291
+ expect(result).toBe('invalid_format');
292
+ });
293
+
294
+ it('should prioritize LC_ALL over other environment variables', () => {
295
+ process.env['LC_ALL'] = 'en_US.UTF-8';
296
+ process.env['LC_CTYPE'] = 'fr_FR.ISO-8859-1';
297
+ process.env['LANG'] = 'de_DE.CP1252';
298
+
299
+ const result = getSystemEncoding();
300
+ expect(result).toBe('utf-8');
301
+ });
302
+
303
+ it('should prioritize LC_CTYPE over LANG', () => {
304
+ process.env['LC_CTYPE'] = 'fr_FR.ISO-8859-1';
305
+ process.env['LANG'] = 'de_DE.CP1252';
306
+
307
+ const result = getSystemEncoding();
308
+ expect(result).toBe('iso-8859-1');
309
+ });
310
+ });
311
+
312
+ describe('getEncodingForBuffer', () => {
313
+ beforeEach(() => {
314
+ mockedOsPlatform.mockReturnValue('linux');
315
+ });
316
+
317
+ it('should use cached system encoding on subsequent calls', () => {
318
+ process.env['LANG'] = 'en_US.UTF-8';
319
+ const buffer = Buffer.from('test');
320
+
321
+ // First call
322
+ const result1 = getCachedEncodingForBuffer(buffer);
323
+ expect(result1).toBe('utf-8');
324
+
325
+ // Change environment (should not affect cached result)
326
+ process.env['LANG'] = 'fr_FR.ISO-8859-1';
327
+
328
+ // Second call should use cached value
329
+ const result2 = getCachedEncodingForBuffer(buffer);
330
+ expect(result2).toBe('utf-8');
331
+ });
332
+
333
+ it('should fall back to buffer detection when system encoding fails', () => {
334
+ // No environment variables set
335
+ mockedExecSync.mockImplementation(() => {
336
+ throw new Error('locale command failed');
337
+ });
338
+
339
+ const buffer = Buffer.from('test');
340
+ mockedChardetDetect.mockReturnValue('ISO-8859-1');
341
+
342
+ const result = getCachedEncodingForBuffer(buffer);
343
+ expect(result).toBe('iso-8859-1');
344
+ expect(mockedChardetDetect).toHaveBeenCalledWith(buffer);
345
+ });
346
+
347
+ it('should fall back to utf-8 when both system and buffer detection fail', () => {
348
+ // System encoding fails
349
+ mockedExecSync.mockImplementation(() => {
350
+ throw new Error('locale command failed');
351
+ });
352
+
353
+ // Buffer detection fails
354
+ mockedChardetDetect.mockImplementation(() => {
355
+ throw new Error('chardet failed');
356
+ });
357
+
358
+ const buffer = Buffer.from('test');
359
+ const result = getCachedEncodingForBuffer(buffer);
360
+ expect(result).toBe('utf-8');
361
+ });
362
+
363
+ it('should not cache buffer detection results', () => {
364
+ // System encoding fails initially
365
+ mockedExecSync.mockImplementation(() => {
366
+ throw new Error('locale command failed');
367
+ });
368
+
369
+ const buffer1 = Buffer.from('test1');
370
+ const buffer2 = Buffer.from('test2');
371
+
372
+ mockedChardetDetect
373
+ .mockReturnValueOnce('ISO-8859-1')
374
+ .mockReturnValueOnce('UTF-16');
375
+
376
+ const result1 = getCachedEncodingForBuffer(buffer1);
377
+ const result2 = getCachedEncodingForBuffer(buffer2);
378
+
379
+ expect(result1).toBe('iso-8859-1');
380
+ expect(result2).toBe('utf-16');
381
+ expect(mockedChardetDetect).toHaveBeenCalledTimes(2);
382
+ });
383
+
384
+ it('should handle Windows system encoding', () => {
385
+ mockedOsPlatform.mockReturnValue('win32');
386
+ mockedExecSync.mockReturnValue('Active code page: 1252');
387
+
388
+ const buffer = Buffer.from('test');
389
+ const result = getCachedEncodingForBuffer(buffer);
390
+
391
+ expect(result).toBe('windows-1252');
392
+ });
393
+
394
+ it('should cache null system encoding result', () => {
395
+ // Reset the cache specifically for this test
396
+ resetEncodingCache();
397
+
398
+ // Ensure we're on Unix-like for this test
399
+ mockedOsPlatform.mockReturnValue('linux');
400
+
401
+ // System encoding detection returns null
402
+ mockedExecSync.mockImplementation(() => {
403
+ throw new Error('locale command failed');
404
+ });
405
+
406
+ const buffer1 = Buffer.from('test1');
407
+ const buffer2 = Buffer.from('test2');
408
+
409
+ mockedChardetDetect
410
+ .mockReturnValueOnce('ISO-8859-1')
411
+ .mockReturnValueOnce('UTF-16');
412
+
413
+ // Clear any previous calls from beforeEach setup or previous tests
414
+ mockedExecSync.mockClear();
415
+
416
+ const result1 = getCachedEncodingForBuffer(buffer1);
417
+ const result2 = getCachedEncodingForBuffer(buffer2);
418
+
419
+ // Should call execSync only once due to caching (null result is cached)
420
+ expect(mockedExecSync).toHaveBeenCalledTimes(1);
421
+ expect(result1).toBe('iso-8859-1');
422
+ expect(result2).toBe('utf-16');
423
+
424
+ // Call a third time to verify cache is still used
425
+ const buffer3 = Buffer.from('test3');
426
+ mockedChardetDetect.mockReturnValueOnce('UTF-32');
427
+ const result3 = getCachedEncodingForBuffer(buffer3);
428
+
429
+ // Still should be only one call to execSync
430
+ expect(mockedExecSync).toHaveBeenCalledTimes(1);
431
+ expect(result3).toBe('utf-32');
432
+ });
433
+ });
434
+
435
+ describe('Cross-platform behavior', () => {
436
+ it('should work correctly on macOS', () => {
437
+ mockedOsPlatform.mockReturnValue('darwin');
438
+ process.env['LANG'] = 'en_US.UTF-8';
439
+
440
+ const result = getSystemEncoding();
441
+ expect(result).toBe('utf-8');
442
+ });
443
+
444
+ it('should work correctly on other Unix-like systems', () => {
445
+ mockedOsPlatform.mockReturnValue('freebsd');
446
+ process.env['LANG'] = 'en_US.UTF-8';
447
+
448
+ const result = getSystemEncoding();
449
+ expect(result).toBe('utf-8');
450
+ });
451
+
452
+ it('should handle unknown platforms as Unix-like', () => {
453
+ mockedOsPlatform.mockReturnValue('unknown' as NodeJS.Platform);
454
+ process.env['LANG'] = 'en_US.UTF-8';
455
+
456
+ const result = getSystemEncoding();
457
+ expect(result).toBe('utf-8');
458
+ });
459
+ });
460
+
461
+ describe('Edge cases and error handling', () => {
462
+ it('should handle empty buffer gracefully', () => {
463
+ mockedOsPlatform.mockReturnValue('linux');
464
+ process.env['LANG'] = 'en_US.UTF-8';
465
+
466
+ const buffer = Buffer.alloc(0);
467
+ const result = getCachedEncodingForBuffer(buffer);
468
+ expect(result).toBe('utf-8');
469
+ });
470
+
471
+ it('should handle very large buffers', () => {
472
+ mockedOsPlatform.mockReturnValue('linux');
473
+ process.env['LANG'] = 'en_US.UTF-8';
474
+
475
+ const buffer = Buffer.alloc(1024 * 1024, 'a');
476
+ const result = getCachedEncodingForBuffer(buffer);
477
+ expect(result).toBe('utf-8');
478
+ });
479
+
480
+ it('should handle Unicode content', () => {
481
+ mockedOsPlatform.mockReturnValue('linux');
482
+ const unicodeText = '你好世界 🌍 ñoño';
483
+
484
+ // System encoding fails
485
+ mockedExecSync.mockImplementation(() => {
486
+ throw new Error('locale command failed');
487
+ });
488
+
489
+ mockedChardetDetect.mockReturnValue('UTF-8');
490
+
491
+ const buffer = Buffer.from(unicodeText, 'utf8');
492
+ const result = getCachedEncodingForBuffer(buffer);
493
+ expect(result).toBe('utf-8');
494
+ });
495
+ });
496
+ });
projects/ui/qwen-code/packages/core/src/utils/systemEncoding.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 { execSync } from 'child_process';
8
+ import os from 'os';
9
+ import { detect as chardetDetect } from 'chardet';
10
+
11
+ // Cache for system encoding to avoid repeated detection
12
+ // Use undefined to indicate "not yet checked" vs null meaning "checked but failed"
13
+ let cachedSystemEncoding: string | null | undefined = undefined;
14
+
15
+ /**
16
+ * Reset the encoding cache - useful for testing
17
+ */
18
+ export function resetEncodingCache(): void {
19
+ cachedSystemEncoding = undefined;
20
+ }
21
+
22
+ /**
23
+ * Returns the system encoding, caching the result to avoid repeated system calls.
24
+ * If system encoding detection fails, falls back to detecting from the provided buffer.
25
+ * Note: Only the system encoding is cached - buffer-based detection runs for each buffer
26
+ * since different buffers may have different encodings.
27
+ * @param buffer A buffer to use for detecting encoding if system detection fails.
28
+ */
29
+ export function getCachedEncodingForBuffer(buffer: Buffer): string {
30
+ // Cache system encoding detection since it's system-wide
31
+ if (cachedSystemEncoding === undefined) {
32
+ cachedSystemEncoding = getSystemEncoding();
33
+ }
34
+
35
+ // If we have a cached system encoding, use it
36
+ if (cachedSystemEncoding) {
37
+ return cachedSystemEncoding;
38
+ }
39
+
40
+ // Otherwise, detect from this specific buffer (don't cache this result)
41
+ return detectEncodingFromBuffer(buffer) || 'utf-8';
42
+ }
43
+
44
+ /**
45
+ * Detects the system encoding based on the platform.
46
+ * For Windows, it uses the 'chcp' command to get the current code page.
47
+ * For Unix-like systems, it checks environment variables like LC_ALL, LC_CTYPE, and LANG.
48
+ * If those are not set, it tries to run 'locale charmap' to get the encoding.
49
+ * If detection fails, it returns null.
50
+ * @returns The system encoding as a string, or null if detection fails.
51
+ */
52
+ export function getSystemEncoding(): string | null {
53
+ // Windows
54
+ if (os.platform() === 'win32') {
55
+ try {
56
+ const output = execSync('chcp', { encoding: 'utf8' });
57
+ const match = output.match(/:\s*(\d+)/);
58
+ if (match) {
59
+ const codePage = parseInt(match[1], 10);
60
+ if (!isNaN(codePage)) {
61
+ return windowsCodePageToEncoding(codePage);
62
+ }
63
+ }
64
+ // Only warn if we can't parse the output format, not if windowsCodePageToEncoding fails
65
+ throw new Error(
66
+ `Unable to parse Windows code page from 'chcp' output "${output.trim()}". `,
67
+ );
68
+ } catch (error) {
69
+ console.warn(
70
+ `Failed to get Windows code page using 'chcp' command: ${error instanceof Error ? error.message : String(error)}. ` +
71
+ `Will attempt to detect encoding from command output instead.`,
72
+ );
73
+ }
74
+ return null;
75
+ }
76
+
77
+ // Unix-like
78
+ // Use environment variables LC_ALL, LC_CTYPE, and LANG to determine the
79
+ // system encoding. However, these environment variables might not always
80
+ // be set or accurate. Handle cases where none of these variables are set.
81
+ const env = process.env;
82
+ let locale = env['LC_ALL'] || env['LC_CTYPE'] || env['LANG'] || '';
83
+
84
+ // Fallback to querying the system directly when environment variables are missing
85
+ if (!locale) {
86
+ try {
87
+ locale = execSync('locale charmap', { encoding: 'utf8' })
88
+ .toString()
89
+ .trim();
90
+ } catch (_e) {
91
+ console.warn('Failed to get locale charmap.');
92
+ return null;
93
+ }
94
+ }
95
+
96
+ const match = locale.match(/\.(.+)/); // e.g., "en_US.UTF-8"
97
+ if (match && match[1]) {
98
+ return match[1].toLowerCase();
99
+ }
100
+
101
+ // Handle cases where locale charmap returns just the encoding name (e.g., "UTF-8")
102
+ if (locale && !locale.includes('.')) {
103
+ return locale.toLowerCase();
104
+ }
105
+
106
+ return null;
107
+ }
108
+
109
+ /**
110
+ * Converts a Windows code page number to a corresponding encoding name.
111
+ * @param cp The Windows code page number (e.g., 437, 850, etc.)
112
+ * @returns The corresponding encoding name as a string, or null if no mapping exists.
113
+ */
114
+ export function windowsCodePageToEncoding(cp: number): string | null {
115
+ // Most common mappings; extend as needed
116
+ const map: { [key: number]: string } = {
117
+ 437: 'cp437',
118
+ 850: 'cp850',
119
+ 852: 'cp852',
120
+ 866: 'cp866',
121
+ 874: 'windows-874',
122
+ 932: 'shift_jis',
123
+ 936: 'gb2312',
124
+ 949: 'euc-kr',
125
+ 950: 'big5',
126
+ 1200: 'utf-16le',
127
+ 1201: 'utf-16be',
128
+ 1250: 'windows-1250',
129
+ 1251: 'windows-1251',
130
+ 1252: 'windows-1252',
131
+ 1253: 'windows-1253',
132
+ 1254: 'windows-1254',
133
+ 1255: 'windows-1255',
134
+ 1256: 'windows-1256',
135
+ 1257: 'windows-1257',
136
+ 1258: 'windows-1258',
137
+ 65001: 'utf-8',
138
+ };
139
+
140
+ if (map[cp]) {
141
+ return map[cp];
142
+ }
143
+
144
+ console.warn(`Unable to determine encoding for windows code page ${cp}.`);
145
+ return null; // Return null if no mapping found
146
+ }
147
+
148
+ /**
149
+ * Attempts to detect encoding from a buffer using chardet.
150
+ * This is useful when system encoding detection fails.
151
+ * Returns the detected encoding in lowercase, or null if detection fails.
152
+ * @param buffer The buffer to analyze for encoding.
153
+ * @return The detected encoding as a lowercase string, or null if detection fails.
154
+ */
155
+ export function detectEncodingFromBuffer(buffer: Buffer): string | null {
156
+ try {
157
+ const detected = chardetDetect(buffer);
158
+ if (detected && typeof detected === 'string') {
159
+ return detected.toLowerCase();
160
+ }
161
+ } catch (error) {
162
+ console.warn('Failed to detect encoding with chardet:', error);
163
+ }
164
+
165
+ return null;
166
+ }
projects/ui/qwen-code/packages/core/src/utils/testUtils.ts ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * Testing utilities for simulating 429 errors in unit tests
9
+ */
10
+
11
+ let requestCounter = 0;
12
+ let simulate429Enabled = false;
13
+ let simulate429AfterRequests = 0;
14
+ let simulate429ForAuthType: string | undefined;
15
+ let fallbackOccurred = false;
16
+
17
+ /**
18
+ * Check if we should simulate a 429 error for the current request
19
+ */
20
+ export function shouldSimulate429(authType?: string): boolean {
21
+ if (!simulate429Enabled || fallbackOccurred) {
22
+ return false;
23
+ }
24
+
25
+ // If auth type filter is set, only simulate for that auth type
26
+ if (simulate429ForAuthType && authType !== simulate429ForAuthType) {
27
+ return false;
28
+ }
29
+
30
+ requestCounter++;
31
+
32
+ // If afterRequests is set, only simulate after that many requests
33
+ if (simulate429AfterRequests > 0) {
34
+ return requestCounter > simulate429AfterRequests;
35
+ }
36
+
37
+ // Otherwise, simulate for every request
38
+ return true;
39
+ }
40
+
41
+ /**
42
+ * Reset the request counter (useful for tests)
43
+ */
44
+ export function resetRequestCounter(): void {
45
+ requestCounter = 0;
46
+ }
47
+
48
+ /**
49
+ * Disable 429 simulation after successful fallback
50
+ */
51
+ export function disableSimulationAfterFallback(): void {
52
+ fallbackOccurred = true;
53
+ }
54
+
55
+ /**
56
+ * Create a simulated 429 error response
57
+ */
58
+ export function createSimulated429Error(): Error {
59
+ const error = new Error('Rate limit exceeded (simulated)') as Error & {
60
+ status: number;
61
+ };
62
+ error.status = 429;
63
+ return error;
64
+ }
65
+
66
+ /**
67
+ * Reset simulation state when switching auth methods
68
+ */
69
+ export function resetSimulationState(): void {
70
+ fallbackOccurred = false;
71
+ resetRequestCounter();
72
+ }
73
+
74
+ /**
75
+ * Enable/disable 429 simulation programmatically (for tests)
76
+ */
77
+ export function setSimulate429(
78
+ enabled: boolean,
79
+ afterRequests = 0,
80
+ forAuthType?: string,
81
+ ): void {
82
+ simulate429Enabled = enabled;
83
+ simulate429AfterRequests = afterRequests;
84
+ simulate429ForAuthType = forAuthType;
85
+ fallbackOccurred = false; // Reset fallback state when simulation is re-enabled
86
+ resetRequestCounter();
87
+ }
projects/ui/qwen-code/packages/core/src/utils/textUtils.ts ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * Checks if a Buffer is likely binary by testing for the presence of a NULL byte.
9
+ * The presence of a NULL byte is a strong indicator that the data is not plain text.
10
+ * @param data The Buffer to check.
11
+ * @param sampleSize The number of bytes from the start of the buffer to test.
12
+ * @returns True if a NULL byte is found, false otherwise.
13
+ */
14
+ export function isBinary(
15
+ data: Buffer | null | undefined,
16
+ sampleSize = 512,
17
+ ): boolean {
18
+ if (!data) {
19
+ return false;
20
+ }
21
+
22
+ const sample = data.length > sampleSize ? data.subarray(0, sampleSize) : data;
23
+
24
+ for (const byte of sample) {
25
+ // The presence of a NULL byte (0x00) is one of the most reliable
26
+ // indicators of a binary file. Text files should not contain them.
27
+ if (byte === 0) {
28
+ return true;
29
+ }
30
+ }
31
+
32
+ // If no NULL bytes were found in the sample, we assume it's text.
33
+ return false;
34
+ }
projects/ui/qwen-code/packages/core/src/utils/user_account.test.ts ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, Mock } from 'vitest';
8
+ import {
9
+ cacheGoogleAccount,
10
+ getCachedGoogleAccount,
11
+ clearCachedGoogleAccount,
12
+ getLifetimeGoogleAccounts,
13
+ } from './user_account.js';
14
+ import * as fs from 'node:fs';
15
+ import * as os from 'node:os';
16
+ import path from 'node:path';
17
+
18
+ vi.mock('os', async (importOriginal) => {
19
+ const os = await importOriginal<typeof import('os')>();
20
+ return {
21
+ ...os,
22
+ homedir: vi.fn(),
23
+ };
24
+ });
25
+
26
+ describe('user_account', () => {
27
+ let tempHomeDir: string;
28
+ const accountsFile = () =>
29
+ path.join(tempHomeDir, '.qwen', 'google_accounts.json');
30
+ beforeEach(() => {
31
+ tempHomeDir = fs.mkdtempSync(
32
+ path.join(os.tmpdir(), 'qwen-code-test-home-'),
33
+ );
34
+ (os.homedir as Mock).mockReturnValue(tempHomeDir);
35
+ });
36
+ afterEach(() => {
37
+ fs.rmSync(tempHomeDir, { recursive: true, force: true });
38
+ vi.clearAllMocks();
39
+ });
40
+
41
+ describe('cacheGoogleAccount', () => {
42
+ it('should create directory and write initial account file', async () => {
43
+ await cacheGoogleAccount('test1@google.com');
44
+
45
+ // Verify Google Account ID was cached
46
+ expect(fs.existsSync(accountsFile())).toBe(true);
47
+ expect(fs.readFileSync(accountsFile(), 'utf-8')).toBe(
48
+ JSON.stringify({ active: 'test1@google.com', old: [] }, null, 2),
49
+ );
50
+ });
51
+
52
+ it('should update active account and move previous to old', async () => {
53
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
54
+ fs.writeFileSync(
55
+ accountsFile(),
56
+ JSON.stringify(
57
+ { active: 'test2@google.com', old: ['test1@google.com'] },
58
+ null,
59
+ 2,
60
+ ),
61
+ );
62
+
63
+ await cacheGoogleAccount('test3@google.com');
64
+
65
+ expect(fs.readFileSync(accountsFile(), 'utf-8')).toBe(
66
+ JSON.stringify(
67
+ {
68
+ active: 'test3@google.com',
69
+ old: ['test1@google.com', 'test2@google.com'],
70
+ },
71
+ null,
72
+ 2,
73
+ ),
74
+ );
75
+ });
76
+
77
+ it('should not add a duplicate to the old list', async () => {
78
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
79
+ fs.writeFileSync(
80
+ accountsFile(),
81
+ JSON.stringify(
82
+ { active: 'test1@google.com', old: ['test2@google.com'] },
83
+ null,
84
+ 2,
85
+ ),
86
+ );
87
+ await cacheGoogleAccount('test2@google.com');
88
+ await cacheGoogleAccount('test1@google.com');
89
+
90
+ expect(fs.readFileSync(accountsFile(), 'utf-8')).toBe(
91
+ JSON.stringify(
92
+ { active: 'test1@google.com', old: ['test2@google.com'] },
93
+ null,
94
+ 2,
95
+ ),
96
+ );
97
+ });
98
+
99
+ it('should handle corrupted JSON by starting fresh', async () => {
100
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
101
+ fs.writeFileSync(accountsFile(), 'not valid json');
102
+ const consoleLogSpy = vi
103
+ .spyOn(console, 'log')
104
+ .mockImplementation(() => {});
105
+
106
+ await cacheGoogleAccount('test1@google.com');
107
+
108
+ expect(consoleLogSpy).toHaveBeenCalled();
109
+ expect(JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'))).toEqual({
110
+ active: 'test1@google.com',
111
+ old: [],
112
+ });
113
+ });
114
+
115
+ it('should handle valid JSON with incorrect schema by starting fresh', async () => {
116
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
117
+ fs.writeFileSync(
118
+ accountsFile(),
119
+ JSON.stringify({ active: 'test1@google.com', old: 'not-an-array' }),
120
+ );
121
+ const consoleLogSpy = vi
122
+ .spyOn(console, 'log')
123
+ .mockImplementation(() => {});
124
+
125
+ await cacheGoogleAccount('test2@google.com');
126
+
127
+ expect(consoleLogSpy).toHaveBeenCalled();
128
+ expect(JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'))).toEqual({
129
+ active: 'test2@google.com',
130
+ old: [],
131
+ });
132
+ });
133
+ });
134
+
135
+ describe('getCachedGoogleAccount', () => {
136
+ it('should return the active account if file exists and is valid', () => {
137
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
138
+ fs.writeFileSync(
139
+ accountsFile(),
140
+ JSON.stringify({ active: 'active@google.com', old: [] }, null, 2),
141
+ );
142
+ const account = getCachedGoogleAccount();
143
+ expect(account).toBe('active@google.com');
144
+ });
145
+
146
+ it('should return null if file does not exist', () => {
147
+ const account = getCachedGoogleAccount();
148
+ expect(account).toBeNull();
149
+ });
150
+
151
+ it('should return null if file is empty', () => {
152
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
153
+ fs.writeFileSync(accountsFile(), '');
154
+ const account = getCachedGoogleAccount();
155
+ expect(account).toBeNull();
156
+ });
157
+
158
+ it('should return null and log if file is corrupted', () => {
159
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
160
+ fs.writeFileSync(accountsFile(), '{ "active": "test@google.com"'); // Invalid JSON
161
+ const consoleLogSpy = vi
162
+ .spyOn(console, 'log')
163
+ .mockImplementation(() => {});
164
+
165
+ const account = getCachedGoogleAccount();
166
+
167
+ expect(account).toBeNull();
168
+ expect(consoleLogSpy).toHaveBeenCalled();
169
+ });
170
+
171
+ it('should return null if active key is missing', () => {
172
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
173
+ fs.writeFileSync(accountsFile(), JSON.stringify({ old: [] }));
174
+ const account = getCachedGoogleAccount();
175
+ expect(account).toBeNull();
176
+ });
177
+ });
178
+
179
+ describe('clearCachedGoogleAccount', () => {
180
+ it('should set active to null and move it to old', async () => {
181
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
182
+ fs.writeFileSync(
183
+ accountsFile(),
184
+ JSON.stringify(
185
+ { active: 'active@google.com', old: ['old1@google.com'] },
186
+ null,
187
+ 2,
188
+ ),
189
+ );
190
+
191
+ await clearCachedGoogleAccount();
192
+
193
+ const stored = JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'));
194
+ expect(stored.active).toBeNull();
195
+ expect(stored.old).toEqual(['old1@google.com', 'active@google.com']);
196
+ });
197
+
198
+ it('should handle empty file gracefully', async () => {
199
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
200
+ fs.writeFileSync(accountsFile(), '');
201
+ await clearCachedGoogleAccount();
202
+ const stored = JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'));
203
+ expect(stored.active).toBeNull();
204
+ expect(stored.old).toEqual([]);
205
+ });
206
+
207
+ it('should handle corrupted JSON by creating a fresh file', async () => {
208
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
209
+ fs.writeFileSync(accountsFile(), 'not valid json');
210
+ const consoleLogSpy = vi
211
+ .spyOn(console, 'log')
212
+ .mockImplementation(() => {});
213
+
214
+ await clearCachedGoogleAccount();
215
+
216
+ expect(consoleLogSpy).toHaveBeenCalled();
217
+ const stored = JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'));
218
+ expect(stored.active).toBeNull();
219
+ expect(stored.old).toEqual([]);
220
+ });
221
+
222
+ it('should be idempotent if active account is already null', async () => {
223
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
224
+ fs.writeFileSync(
225
+ accountsFile(),
226
+ JSON.stringify({ active: null, old: ['old1@google.com'] }, null, 2),
227
+ );
228
+
229
+ await clearCachedGoogleAccount();
230
+
231
+ const stored = JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'));
232
+ expect(stored.active).toBeNull();
233
+ expect(stored.old).toEqual(['old1@google.com']);
234
+ });
235
+
236
+ it('should not add a duplicate to the old list', async () => {
237
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
238
+ fs.writeFileSync(
239
+ accountsFile(),
240
+ JSON.stringify(
241
+ {
242
+ active: 'active@google.com',
243
+ old: ['active@google.com'],
244
+ },
245
+ null,
246
+ 2,
247
+ ),
248
+ );
249
+
250
+ await clearCachedGoogleAccount();
251
+
252
+ const stored = JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'));
253
+ expect(stored.active).toBeNull();
254
+ expect(stored.old).toEqual(['active@google.com']);
255
+ });
256
+ });
257
+
258
+ describe('getLifetimeGoogleAccounts', () => {
259
+ it('should return 0 if the file does not exist', () => {
260
+ expect(getLifetimeGoogleAccounts()).toBe(0);
261
+ });
262
+
263
+ it('should return 0 if the file is empty', () => {
264
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
265
+ fs.writeFileSync(accountsFile(), '');
266
+ expect(getLifetimeGoogleAccounts()).toBe(0);
267
+ });
268
+
269
+ it('should return 0 if the file is corrupted', () => {
270
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
271
+ fs.writeFileSync(accountsFile(), 'invalid json');
272
+ const consoleLogSpy = vi
273
+ .spyOn(console, 'log')
274
+ .mockImplementation(() => {});
275
+
276
+ expect(getLifetimeGoogleAccounts()).toBe(0);
277
+ expect(consoleLogSpy).toHaveBeenCalled();
278
+ });
279
+
280
+ it('should return 1 if there is only an active account', () => {
281
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
282
+ fs.writeFileSync(
283
+ accountsFile(),
284
+ JSON.stringify({ active: 'test1@google.com', old: [] }),
285
+ );
286
+ expect(getLifetimeGoogleAccounts()).toBe(1);
287
+ });
288
+
289
+ it('should correctly count old accounts when active is null', () => {
290
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
291
+ fs.writeFileSync(
292
+ accountsFile(),
293
+ JSON.stringify({
294
+ active: null,
295
+ old: ['test1@google.com', 'test2@google.com'],
296
+ }),
297
+ );
298
+ expect(getLifetimeGoogleAccounts()).toBe(2);
299
+ });
300
+
301
+ it('should correctly count both active and old accounts', () => {
302
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
303
+ fs.writeFileSync(
304
+ accountsFile(),
305
+ JSON.stringify({
306
+ active: 'test3@google.com',
307
+ old: ['test1@google.com', 'test2@google.com'],
308
+ }),
309
+ );
310
+ expect(getLifetimeGoogleAccounts()).toBe(3);
311
+ });
312
+
313
+ it('should handle valid JSON with incorrect schema by returning 0', () => {
314
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
315
+ fs.writeFileSync(
316
+ accountsFile(),
317
+ JSON.stringify({ active: null, old: 1 }),
318
+ );
319
+ const consoleLogSpy = vi
320
+ .spyOn(console, 'log')
321
+ .mockImplementation(() => {});
322
+
323
+ expect(getLifetimeGoogleAccounts()).toBe(0);
324
+ expect(consoleLogSpy).toHaveBeenCalled();
325
+ });
326
+
327
+ it('should not double count if active account is also in old list', () => {
328
+ fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
329
+ fs.writeFileSync(
330
+ accountsFile(),
331
+ JSON.stringify({
332
+ active: 'test1@google.com',
333
+ old: ['test1@google.com', 'test2@google.com'],
334
+ }),
335
+ );
336
+ expect(getLifetimeGoogleAccounts()).toBe(2);
337
+ });
338
+ });
339
+ });
projects/ui/qwen-code/packages/core/src/utils/user_account.ts ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { promises as fsp, readFileSync } from 'node:fs';
9
+ import * as os from 'os';
10
+ import { QWEN_DIR, GOOGLE_ACCOUNTS_FILENAME } from './paths.js';
11
+
12
+ interface UserAccounts {
13
+ active: string | null;
14
+ old: string[];
15
+ }
16
+
17
+ function getGoogleAccountsCachePath(): string {
18
+ return path.join(os.homedir(), QWEN_DIR, GOOGLE_ACCOUNTS_FILENAME);
19
+ }
20
+
21
+ /**
22
+ * Parses and validates the string content of an accounts file.
23
+ * @param content The raw string content from the file.
24
+ * @returns A valid UserAccounts object.
25
+ */
26
+ function parseAndValidateAccounts(content: string): UserAccounts {
27
+ const defaultState = { active: null, old: [] };
28
+ if (!content.trim()) {
29
+ return defaultState;
30
+ }
31
+
32
+ const parsed = JSON.parse(content);
33
+
34
+ // Inlined validation logic
35
+ if (typeof parsed !== 'object' || parsed === null) {
36
+ console.log('Invalid accounts file schema, starting fresh.');
37
+ return defaultState;
38
+ }
39
+ const { active, old } = parsed as Partial<UserAccounts>;
40
+ const isValid =
41
+ (active === undefined || active === null || typeof active === 'string') &&
42
+ (old === undefined ||
43
+ (Array.isArray(old) && old.every((i) => typeof i === 'string')));
44
+
45
+ if (!isValid) {
46
+ console.log('Invalid accounts file schema, starting fresh.');
47
+ return defaultState;
48
+ }
49
+
50
+ return {
51
+ active: parsed.active ?? null,
52
+ old: parsed.old ?? [],
53
+ };
54
+ }
55
+
56
+ function readAccountsSync(filePath: string): UserAccounts {
57
+ const defaultState = { active: null, old: [] };
58
+ try {
59
+ const content = readFileSync(filePath, 'utf-8');
60
+ return parseAndValidateAccounts(content);
61
+ } catch (error) {
62
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
63
+ return defaultState;
64
+ }
65
+ console.log('Error during sync read of accounts, starting fresh.', error);
66
+ return defaultState;
67
+ }
68
+ }
69
+
70
+ async function readAccounts(filePath: string): Promise<UserAccounts> {
71
+ const defaultState = { active: null, old: [] };
72
+ try {
73
+ const content = await fsp.readFile(filePath, 'utf-8');
74
+ return parseAndValidateAccounts(content);
75
+ } catch (error) {
76
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
77
+ return defaultState;
78
+ }
79
+ console.log('Could not parse accounts file, starting fresh.', error);
80
+ return defaultState;
81
+ }
82
+ }
83
+
84
+ export async function cacheGoogleAccount(email: string): Promise<void> {
85
+ const filePath = getGoogleAccountsCachePath();
86
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
87
+
88
+ const accounts = await readAccounts(filePath);
89
+
90
+ if (accounts.active && accounts.active !== email) {
91
+ if (!accounts.old.includes(accounts.active)) {
92
+ accounts.old.push(accounts.active);
93
+ }
94
+ }
95
+
96
+ // If the new email was in the old list, remove it
97
+ accounts.old = accounts.old.filter((oldEmail) => oldEmail !== email);
98
+
99
+ accounts.active = email;
100
+ await fsp.writeFile(filePath, JSON.stringify(accounts, null, 2), 'utf-8');
101
+ }
102
+
103
+ export function getCachedGoogleAccount(): string | null {
104
+ const filePath = getGoogleAccountsCachePath();
105
+ const accounts = readAccountsSync(filePath);
106
+ return accounts.active;
107
+ }
108
+
109
+ export function getLifetimeGoogleAccounts(): number {
110
+ const filePath = getGoogleAccountsCachePath();
111
+ const accounts = readAccountsSync(filePath);
112
+ const allAccounts = new Set(accounts.old);
113
+ if (accounts.active) {
114
+ allAccounts.add(accounts.active);
115
+ }
116
+ return allAccounts.size;
117
+ }
118
+
119
+ export async function clearCachedGoogleAccount(): Promise<void> {
120
+ const filePath = getGoogleAccountsCachePath();
121
+ const accounts = await readAccounts(filePath);
122
+
123
+ if (accounts.active) {
124
+ if (!accounts.old.includes(accounts.active)) {
125
+ accounts.old.push(accounts.active);
126
+ }
127
+ accounts.active = null;
128
+ }
129
+
130
+ await fsp.writeFile(filePath, JSON.stringify(accounts, null, 2), 'utf-8');
131
+ }
projects/ui/qwen-code/packages/core/src/utils/user_id.test.ts ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { getInstallationId } from './user_id.js';
9
+
10
+ describe('user_id', () => {
11
+ describe('getInstallationId', () => {
12
+ it('should return a valid UUID format string', () => {
13
+ const installationId = getInstallationId();
14
+
15
+ expect(installationId).toBeDefined();
16
+ expect(typeof installationId).toBe('string');
17
+ expect(installationId.length).toBeGreaterThan(0);
18
+
19
+ // Should return the same ID on subsequent calls (consistent)
20
+ const secondCall = getInstallationId();
21
+ expect(secondCall).toBe(installationId);
22
+ });
23
+ });
24
+ });
projects/ui/qwen-code/packages/core/src/utils/user_id.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as os from 'os';
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
10
+ import { randomUUID } from 'crypto';
11
+ import { QWEN_DIR } from './paths.js';
12
+
13
+ const homeDir = os.homedir() ?? '';
14
+ const geminiDir = path.join(homeDir, QWEN_DIR);
15
+ const installationIdFile = path.join(geminiDir, 'installation_id');
16
+
17
+ function ensureGeminiDirExists() {
18
+ if (!fs.existsSync(geminiDir)) {
19
+ fs.mkdirSync(geminiDir, { recursive: true });
20
+ }
21
+ }
22
+
23
+ function readInstallationIdFromFile(): string | null {
24
+ if (fs.existsSync(installationIdFile)) {
25
+ const installationid = fs.readFileSync(installationIdFile, 'utf-8').trim();
26
+ return installationid || null;
27
+ }
28
+ return null;
29
+ }
30
+
31
+ function writeInstallationIdToFile(installationId: string) {
32
+ fs.writeFileSync(installationIdFile, installationId, 'utf-8');
33
+ }
34
+
35
+ /**
36
+ * Retrieves the installation ID from a file, creating it if it doesn't exist.
37
+ * This ID is used for unique user installation tracking.
38
+ * @returns A UUID string for the user.
39
+ */
40
+ export function getInstallationId(): string {
41
+ try {
42
+ ensureGeminiDirExists();
43
+ let installationId = readInstallationIdFromFile();
44
+
45
+ if (!installationId) {
46
+ installationId = randomUUID();
47
+ writeInstallationIdToFile(installationId);
48
+ }
49
+
50
+ return installationId;
51
+ } catch (error) {
52
+ console.error(
53
+ 'Error accessing installation ID file, generating ephemeral ID:',
54
+ error,
55
+ );
56
+ return '123456789';
57
+ }
58
+ }
projects/ui/qwen-code/packages/core/src/utils/workspaceContext.test.ts ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
8
+ import * as fs from 'fs';
9
+ import * as os from 'os';
10
+ import * as path from 'path';
11
+ import { WorkspaceContext } from './workspaceContext.js';
12
+
13
+ describe('WorkspaceContext with real filesystem', () => {
14
+ let tempDir: string;
15
+ let cwd: string;
16
+ let otherDir: string;
17
+
18
+ beforeEach(() => {
19
+ // os.tmpdir() can return a path using a symlink (this is standard on macOS)
20
+ // Use fs.realpathSync to fully resolve the absolute path.
21
+ tempDir = fs.realpathSync(
22
+ fs.mkdtempSync(path.join(os.tmpdir(), 'workspace-context-test-')),
23
+ );
24
+
25
+ cwd = path.join(tempDir, 'project');
26
+ otherDir = path.join(tempDir, 'other-project');
27
+
28
+ fs.mkdirSync(cwd, { recursive: true });
29
+ fs.mkdirSync(otherDir, { recursive: true });
30
+ });
31
+
32
+ afterEach(() => {
33
+ fs.rmSync(tempDir, { recursive: true, force: true });
34
+ });
35
+
36
+ describe('initialization', () => {
37
+ it('should initialize with a single directory (cwd)', () => {
38
+ const workspaceContext = new WorkspaceContext(cwd);
39
+ const directories = workspaceContext.getDirectories();
40
+
41
+ expect(directories).toEqual([cwd]);
42
+ });
43
+
44
+ it('should validate and resolve directories to absolute paths', () => {
45
+ const workspaceContext = new WorkspaceContext(cwd, [otherDir]);
46
+ const directories = workspaceContext.getDirectories();
47
+
48
+ expect(directories).toEqual([cwd, otherDir]);
49
+ });
50
+
51
+ it('should reject non-existent directories', () => {
52
+ const nonExistentDir = path.join(tempDir, 'does-not-exist');
53
+ expect(() => {
54
+ new WorkspaceContext(cwd, [nonExistentDir]);
55
+ }).toThrow('Directory does not exist');
56
+ });
57
+
58
+ it('should handle empty initialization', () => {
59
+ const workspaceContext = new WorkspaceContext(cwd, []);
60
+ const directories = workspaceContext.getDirectories();
61
+ expect(directories).toHaveLength(1);
62
+ expect(fs.realpathSync(directories[0])).toBe(cwd);
63
+ });
64
+ });
65
+
66
+ describe('adding directories', () => {
67
+ it('should add valid directories', () => {
68
+ const workspaceContext = new WorkspaceContext(cwd);
69
+ workspaceContext.addDirectory(otherDir);
70
+ const directories = workspaceContext.getDirectories();
71
+
72
+ expect(directories).toEqual([cwd, otherDir]);
73
+ });
74
+
75
+ it('should resolve relative paths to absolute', () => {
76
+ const workspaceContext = new WorkspaceContext(cwd);
77
+ const relativePath = path.relative(cwd, otherDir);
78
+ workspaceContext.addDirectory(relativePath, cwd);
79
+ const directories = workspaceContext.getDirectories();
80
+
81
+ expect(directories).toEqual([cwd, otherDir]);
82
+ });
83
+
84
+ it('should reject non-existent directories', () => {
85
+ const nonExistentDir = path.join(tempDir, 'does-not-exist');
86
+ const workspaceContext = new WorkspaceContext(cwd);
87
+
88
+ expect(() => {
89
+ workspaceContext.addDirectory(nonExistentDir);
90
+ }).toThrow('Directory does not exist');
91
+ });
92
+
93
+ it('should prevent duplicate directories', () => {
94
+ const workspaceContext = new WorkspaceContext(cwd);
95
+ workspaceContext.addDirectory(otherDir);
96
+ workspaceContext.addDirectory(otherDir);
97
+ const directories = workspaceContext.getDirectories();
98
+
99
+ expect(directories).toHaveLength(2);
100
+ });
101
+
102
+ it('should handle symbolic links correctly', () => {
103
+ const realDir = path.join(tempDir, 'real');
104
+ fs.mkdirSync(realDir, { recursive: true });
105
+ const symlinkDir = path.join(tempDir, 'symlink-to-real');
106
+ fs.symlinkSync(realDir, symlinkDir, 'dir');
107
+ const workspaceContext = new WorkspaceContext(cwd);
108
+ workspaceContext.addDirectory(symlinkDir);
109
+
110
+ const directories = workspaceContext.getDirectories();
111
+
112
+ expect(directories).toEqual([cwd, realDir]);
113
+ });
114
+ });
115
+
116
+ describe('path validation', () => {
117
+ it('should accept paths within workspace directories', () => {
118
+ const workspaceContext = new WorkspaceContext(cwd, [otherDir]);
119
+ const validPath1 = path.join(cwd, 'src', 'file.ts');
120
+ const validPath2 = path.join(otherDir, 'lib', 'module.js');
121
+
122
+ fs.mkdirSync(path.dirname(validPath1), { recursive: true });
123
+ fs.writeFileSync(validPath1, 'content');
124
+ fs.mkdirSync(path.dirname(validPath2), { recursive: true });
125
+ fs.writeFileSync(validPath2, 'content');
126
+
127
+ expect(workspaceContext.isPathWithinWorkspace(validPath1)).toBe(true);
128
+ expect(workspaceContext.isPathWithinWorkspace(validPath2)).toBe(true);
129
+ });
130
+
131
+ it('should accept non-existent paths within workspace directories', () => {
132
+ const workspaceContext = new WorkspaceContext(cwd, [otherDir]);
133
+ const validPath1 = path.join(cwd, 'src', 'file.ts');
134
+ const validPath2 = path.join(otherDir, 'lib', 'module.js');
135
+
136
+ expect(workspaceContext.isPathWithinWorkspace(validPath1)).toBe(true);
137
+ expect(workspaceContext.isPathWithinWorkspace(validPath2)).toBe(true);
138
+ });
139
+
140
+ it('should reject paths outside workspace', () => {
141
+ const workspaceContext = new WorkspaceContext(cwd, [otherDir]);
142
+ const invalidPath = path.join(tempDir, 'outside-workspace', 'file.txt');
143
+
144
+ expect(workspaceContext.isPathWithinWorkspace(invalidPath)).toBe(false);
145
+ });
146
+
147
+ it('should reject non-existent paths outside workspace', () => {
148
+ const workspaceContext = new WorkspaceContext(cwd, [otherDir]);
149
+ const invalidPath = path.join(tempDir, 'outside-workspace', 'file.txt');
150
+
151
+ expect(workspaceContext.isPathWithinWorkspace(invalidPath)).toBe(false);
152
+ });
153
+
154
+ it('should handle nested directories correctly', () => {
155
+ const workspaceContext = new WorkspaceContext(cwd, [otherDir]);
156
+ const nestedPath = path.join(cwd, 'deeply', 'nested', 'path', 'file.txt');
157
+ expect(workspaceContext.isPathWithinWorkspace(nestedPath)).toBe(true);
158
+ });
159
+
160
+ it('should handle edge cases (root, parent references)', () => {
161
+ const workspaceContext = new WorkspaceContext(cwd, [otherDir]);
162
+ const rootPath = path.parse(tempDir).root;
163
+ const parentPath = path.dirname(cwd);
164
+
165
+ expect(workspaceContext.isPathWithinWorkspace(rootPath)).toBe(false);
166
+ expect(workspaceContext.isPathWithinWorkspace(parentPath)).toBe(false);
167
+ });
168
+
169
+ it('should handle non-existent paths correctly', () => {
170
+ const workspaceContext = new WorkspaceContext(cwd, [otherDir]);
171
+ const nonExistentPath = path.join(cwd, 'does-not-exist.txt');
172
+ expect(workspaceContext.isPathWithinWorkspace(nonExistentPath)).toBe(
173
+ true,
174
+ );
175
+ });
176
+
177
+ describe('with symbolic link', () => {
178
+ describe('in the workspace', () => {
179
+ let realDir: string;
180
+ let symlinkDir: string;
181
+ beforeEach(() => {
182
+ realDir = path.join(cwd, 'real-dir');
183
+ fs.mkdirSync(realDir, { recursive: true });
184
+
185
+ symlinkDir = path.join(cwd, 'symlink-file');
186
+ fs.symlinkSync(realDir, symlinkDir, 'dir');
187
+ });
188
+
189
+ it('should accept dir paths', () => {
190
+ const workspaceContext = new WorkspaceContext(cwd);
191
+
192
+ expect(workspaceContext.isPathWithinWorkspace(symlinkDir)).toBe(true);
193
+ });
194
+
195
+ it('should accept non-existent paths', () => {
196
+ const filePath = path.join(symlinkDir, 'does-not-exist.txt');
197
+
198
+ const workspaceContext = new WorkspaceContext(cwd);
199
+
200
+ expect(workspaceContext.isPathWithinWorkspace(filePath)).toBe(true);
201
+ });
202
+
203
+ it('should accept non-existent deep paths', () => {
204
+ const filePath = path.join(symlinkDir, 'deep', 'does-not-exist.txt');
205
+
206
+ const workspaceContext = new WorkspaceContext(cwd);
207
+
208
+ expect(workspaceContext.isPathWithinWorkspace(filePath)).toBe(true);
209
+ });
210
+ });
211
+
212
+ describe('outside the workspace', () => {
213
+ let realDir: string;
214
+ let symlinkDir: string;
215
+ beforeEach(() => {
216
+ realDir = path.join(tempDir, 'real-dir');
217
+ fs.mkdirSync(realDir, { recursive: true });
218
+
219
+ symlinkDir = path.join(cwd, 'symlink-file');
220
+ fs.symlinkSync(realDir, symlinkDir, 'dir');
221
+ });
222
+
223
+ it('should reject dir paths', () => {
224
+ const workspaceContext = new WorkspaceContext(cwd);
225
+
226
+ expect(workspaceContext.isPathWithinWorkspace(symlinkDir)).toBe(
227
+ false,
228
+ );
229
+ });
230
+
231
+ it('should reject non-existent paths', () => {
232
+ const filePath = path.join(symlinkDir, 'does-not-exist.txt');
233
+
234
+ const workspaceContext = new WorkspaceContext(cwd);
235
+
236
+ expect(workspaceContext.isPathWithinWorkspace(filePath)).toBe(false);
237
+ });
238
+
239
+ it('should reject non-existent deep paths', () => {
240
+ const filePath = path.join(symlinkDir, 'deep', 'does-not-exist.txt');
241
+
242
+ const workspaceContext = new WorkspaceContext(cwd);
243
+
244
+ expect(workspaceContext.isPathWithinWorkspace(filePath)).toBe(false);
245
+ });
246
+
247
+ it('should reject partially non-existent deep paths', () => {
248
+ const deepDir = path.join(symlinkDir, 'deep');
249
+ fs.mkdirSync(deepDir, { recursive: true });
250
+ const filePath = path.join(deepDir, 'does-not-exist.txt');
251
+
252
+ const workspaceContext = new WorkspaceContext(cwd);
253
+
254
+ expect(workspaceContext.isPathWithinWorkspace(filePath)).toBe(false);
255
+ });
256
+ });
257
+
258
+ it('should reject symbolic file links outside the workspace', () => {
259
+ const realFile = path.join(tempDir, 'real-file.txt');
260
+ fs.writeFileSync(realFile, 'content');
261
+
262
+ const symlinkFile = path.join(cwd, 'symlink-to-real-file');
263
+ fs.symlinkSync(realFile, symlinkFile, 'file');
264
+
265
+ const workspaceContext = new WorkspaceContext(cwd);
266
+
267
+ expect(workspaceContext.isPathWithinWorkspace(symlinkFile)).toBe(false);
268
+ });
269
+
270
+ it('should reject non-existent symbolic file links outside the workspace', () => {
271
+ const realFile = path.join(tempDir, 'real-file.txt');
272
+
273
+ const symlinkFile = path.join(cwd, 'symlink-to-real-file');
274
+ fs.symlinkSync(realFile, symlinkFile, 'file');
275
+
276
+ const workspaceContext = new WorkspaceContext(cwd);
277
+
278
+ expect(workspaceContext.isPathWithinWorkspace(symlinkFile)).toBe(false);
279
+ });
280
+
281
+ it('should handle circular symlinks gracefully', () => {
282
+ const workspaceContext = new WorkspaceContext(cwd);
283
+ const linkA = path.join(cwd, 'link-a');
284
+ const linkB = path.join(cwd, 'link-b');
285
+ // Create a circular dependency: linkA -> linkB -> linkA
286
+ fs.symlinkSync(linkB, linkA, 'dir');
287
+ fs.symlinkSync(linkA, linkB, 'dir');
288
+
289
+ // fs.realpathSync should throw ELOOP, and isPathWithinWorkspace should
290
+ // handle it gracefully and return false.
291
+ expect(workspaceContext.isPathWithinWorkspace(linkA)).toBe(false);
292
+ expect(workspaceContext.isPathWithinWorkspace(linkB)).toBe(false);
293
+ });
294
+ });
295
+ });
296
+
297
+ describe('onDirectoriesChanged', () => {
298
+ it('should call listener when adding a directory', () => {
299
+ const workspaceContext = new WorkspaceContext(cwd);
300
+ const listener = vi.fn();
301
+ workspaceContext.onDirectoriesChanged(listener);
302
+
303
+ workspaceContext.addDirectory(otherDir);
304
+
305
+ expect(listener).toHaveBeenCalledOnce();
306
+ });
307
+
308
+ it('should not call listener when adding a duplicate directory', () => {
309
+ const workspaceContext = new WorkspaceContext(cwd);
310
+ workspaceContext.addDirectory(otherDir);
311
+ const listener = vi.fn();
312
+ workspaceContext.onDirectoriesChanged(listener);
313
+
314
+ workspaceContext.addDirectory(otherDir);
315
+
316
+ expect(listener).not.toHaveBeenCalled();
317
+ });
318
+
319
+ it('should call listener when setting different directories', () => {
320
+ const workspaceContext = new WorkspaceContext(cwd);
321
+ const listener = vi.fn();
322
+ workspaceContext.onDirectoriesChanged(listener);
323
+
324
+ workspaceContext.setDirectories([otherDir]);
325
+
326
+ expect(listener).toHaveBeenCalledOnce();
327
+ });
328
+
329
+ it('should not call listener when setting same directories', () => {
330
+ const workspaceContext = new WorkspaceContext(cwd);
331
+ const listener = vi.fn();
332
+ workspaceContext.onDirectoriesChanged(listener);
333
+
334
+ workspaceContext.setDirectories([cwd]);
335
+
336
+ expect(listener).not.toHaveBeenCalled();
337
+ });
338
+
339
+ it('should support multiple listeners', () => {
340
+ const workspaceContext = new WorkspaceContext(cwd);
341
+ const listener1 = vi.fn();
342
+ const listener2 = vi.fn();
343
+ workspaceContext.onDirectoriesChanged(listener1);
344
+ workspaceContext.onDirectoriesChanged(listener2);
345
+
346
+ workspaceContext.addDirectory(otherDir);
347
+
348
+ expect(listener1).toHaveBeenCalledOnce();
349
+ expect(listener2).toHaveBeenCalledOnce();
350
+ });
351
+
352
+ it('should allow unsubscribing a listener', () => {
353
+ const workspaceContext = new WorkspaceContext(cwd);
354
+ const listener = vi.fn();
355
+ const unsubscribe = workspaceContext.onDirectoriesChanged(listener);
356
+
357
+ unsubscribe();
358
+ workspaceContext.addDirectory(otherDir);
359
+
360
+ expect(listener).not.toHaveBeenCalled();
361
+ });
362
+
363
+ it('should not fail if a listener throws an error', () => {
364
+ const workspaceContext = new WorkspaceContext(cwd);
365
+ const errorListener = () => {
366
+ throw new Error('test error');
367
+ };
368
+ const listener = vi.fn();
369
+ workspaceContext.onDirectoriesChanged(errorListener);
370
+ workspaceContext.onDirectoriesChanged(listener);
371
+
372
+ expect(() => {
373
+ workspaceContext.addDirectory(otherDir);
374
+ }).not.toThrow();
375
+ expect(listener).toHaveBeenCalledOnce();
376
+ });
377
+ });
378
+
379
+ describe('getDirectories', () => {
380
+ it('should return a copy of directories array', () => {
381
+ const workspaceContext = new WorkspaceContext(cwd);
382
+ const dirs1 = workspaceContext.getDirectories();
383
+ const dirs2 = workspaceContext.getDirectories();
384
+
385
+ expect(dirs1).not.toBe(dirs2);
386
+ expect(dirs1).toEqual(dirs2);
387
+ });
388
+ });
389
+ });
projects/ui/qwen-code/packages/core/src/utils/workspaceContext.ts ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { isNodeError } from '../utils/errors.js';
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
10
+
11
+ export type Unsubscribe = () => void;
12
+
13
+ /**
14
+ * WorkspaceContext manages multiple workspace directories and validates paths
15
+ * against them. This allows the CLI to operate on files from multiple directories
16
+ * in a single session.
17
+ */
18
+ export class WorkspaceContext {
19
+ private directories = new Set<string>();
20
+ private initialDirectories: Set<string>;
21
+ private onDirectoriesChangedListeners = new Set<() => void>();
22
+
23
+ /**
24
+ * Creates a new WorkspaceContext with the given initial directory and optional additional directories.
25
+ * @param directory The initial working directory (usually cwd)
26
+ * @param additionalDirectories Optional array of additional directories to include
27
+ */
28
+ constructor(directory: string, additionalDirectories: string[] = []) {
29
+ this.addDirectory(directory);
30
+ for (const additionalDirectory of additionalDirectories) {
31
+ this.addDirectory(additionalDirectory);
32
+ }
33
+
34
+ this.initialDirectories = new Set(this.directories);
35
+ }
36
+
37
+ /**
38
+ * Registers a listener that is called when the workspace directories change.
39
+ * @param listener The listener to call.
40
+ * @returns A function to unsubscribe the listener.
41
+ */
42
+ onDirectoriesChanged(listener: () => void): Unsubscribe {
43
+ this.onDirectoriesChangedListeners.add(listener);
44
+ return () => {
45
+ this.onDirectoriesChangedListeners.delete(listener);
46
+ };
47
+ }
48
+
49
+ private notifyDirectoriesChanged() {
50
+ // Iterate over a copy of the set in case a listener unsubscribes itself or others.
51
+ for (const listener of [...this.onDirectoriesChangedListeners]) {
52
+ try {
53
+ listener();
54
+ } catch (e) {
55
+ // Don't let one listener break others.
56
+ console.error('Error in WorkspaceContext listener:', e);
57
+ }
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Adds a directory to the workspace.
63
+ * @param directory The directory path to add (can be relative or absolute)
64
+ * @param basePath Optional base path for resolving relative paths (defaults to cwd)
65
+ */
66
+ addDirectory(directory: string, basePath: string = process.cwd()): void {
67
+ const resolved = this.resolveAndValidateDir(directory, basePath);
68
+ if (this.directories.has(resolved)) {
69
+ return;
70
+ }
71
+ this.directories.add(resolved);
72
+ this.notifyDirectoriesChanged();
73
+ }
74
+
75
+ private resolveAndValidateDir(
76
+ directory: string,
77
+ basePath: string = process.cwd(),
78
+ ): string {
79
+ const absolutePath = path.isAbsolute(directory)
80
+ ? directory
81
+ : path.resolve(basePath, directory);
82
+
83
+ if (!fs.existsSync(absolutePath)) {
84
+ throw new Error(`Directory does not exist: ${absolutePath}`);
85
+ }
86
+ const stats = fs.statSync(absolutePath);
87
+ if (!stats.isDirectory()) {
88
+ throw new Error(`Path is not a directory: ${absolutePath}`);
89
+ }
90
+
91
+ return fs.realpathSync(absolutePath);
92
+ }
93
+
94
+ /**
95
+ * Gets a copy of all workspace directories.
96
+ * @returns Array of absolute directory paths
97
+ */
98
+ getDirectories(): readonly string[] {
99
+ return Array.from(this.directories);
100
+ }
101
+
102
+ getInitialDirectories(): readonly string[] {
103
+ return Array.from(this.initialDirectories);
104
+ }
105
+
106
+ setDirectories(directories: readonly string[]): void {
107
+ const newDirectories = new Set<string>();
108
+ for (const dir of directories) {
109
+ newDirectories.add(this.resolveAndValidateDir(dir));
110
+ }
111
+
112
+ if (
113
+ newDirectories.size !== this.directories.size ||
114
+ ![...newDirectories].every((d) => this.directories.has(d))
115
+ ) {
116
+ this.directories = newDirectories;
117
+ this.notifyDirectoriesChanged();
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Checks if a given path is within any of the workspace directories.
123
+ * @param pathToCheck The path to validate
124
+ * @returns True if the path is within the workspace, false otherwise
125
+ */
126
+ isPathWithinWorkspace(pathToCheck: string): boolean {
127
+ try {
128
+ const fullyResolvedPath = this.fullyResolvedPath(pathToCheck);
129
+
130
+ for (const dir of this.directories) {
131
+ if (this.isPathWithinRoot(fullyResolvedPath, dir)) {
132
+ return true;
133
+ }
134
+ }
135
+ return false;
136
+ } catch (_error) {
137
+ return false;
138
+ }
139
+ }
140
+
141
+ /**
142
+ * Fully resolves a path, including symbolic links.
143
+ * If the path does not exist, it returns the fully resolved path as it would be
144
+ * if it did exist.
145
+ */
146
+ private fullyResolvedPath(pathToCheck: string): string {
147
+ try {
148
+ return fs.realpathSync(pathToCheck);
149
+ } catch (e: unknown) {
150
+ if (
151
+ isNodeError(e) &&
152
+ e.code === 'ENOENT' &&
153
+ e.path &&
154
+ // realpathSync does not set e.path correctly for symlinks to
155
+ // non-existent files.
156
+ !this.isFileSymlink(e.path)
157
+ ) {
158
+ // If it doesn't exist, e.path contains the fully resolved path.
159
+ return e.path;
160
+ }
161
+ throw e;
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Checks if a path is within a given root directory.
167
+ * @param pathToCheck The absolute path to check
168
+ * @param rootDirectory The absolute root directory
169
+ * @returns True if the path is within the root directory, false otherwise
170
+ */
171
+ private isPathWithinRoot(
172
+ pathToCheck: string,
173
+ rootDirectory: string,
174
+ ): boolean {
175
+ const relative = path.relative(rootDirectory, pathToCheck);
176
+ return (
177
+ !relative.startsWith(`..${path.sep}`) &&
178
+ relative !== '..' &&
179
+ !path.isAbsolute(relative)
180
+ );
181
+ }
182
+
183
+ /**
184
+ * Checks if a file path is a symbolic link that points to a file.
185
+ */
186
+ private isFileSymlink(filePath: string): boolean {
187
+ try {
188
+ return !fs.readlinkSync(filePath).endsWith('/');
189
+ } catch (_error) {
190
+ return false;
191
+ }
192
+ }
193
+ }