ADAPT-Chase commited on
Commit
9defff4
·
verified ·
1 Parent(s): ccd9038

Add files using upload-large-folder tool

Browse files
Files changed (20) hide show
  1. projects/ui/qwen-code/packages/core/src/qwen/qwenOAuth2.test.ts +2277 -0
  2. projects/ui/qwen-code/packages/core/src/qwen/qwenOAuth2.ts +884 -0
  3. projects/ui/qwen-code/packages/core/src/qwen/sharedTokenManager.test.ts +758 -0
  4. projects/ui/qwen-code/packages/core/src/qwen/sharedTokenManager.ts +662 -0
  5. projects/ui/qwen-code/packages/core/src/services/chatRecordingService.test.ts +367 -0
  6. projects/ui/qwen-code/packages/core/src/services/chatRecordingService.ts +433 -0
  7. projects/ui/qwen-code/packages/core/src/services/fileDiscoveryService.test.ts +211 -0
  8. projects/ui/qwen-code/packages/core/src/services/fileDiscoveryService.ts +111 -0
  9. projects/ui/qwen-code/packages/core/src/services/fileSystemService.test.ts +59 -0
  10. projects/ui/qwen-code/packages/core/src/services/fileSystemService.ts +41 -0
  11. projects/ui/qwen-code/packages/core/src/services/gitService.test.ts +247 -0
  12. projects/ui/qwen-code/packages/core/src/services/gitService.ts +120 -0
  13. projects/ui/qwen-code/packages/core/src/services/loopDetectionService.test.ts +700 -0
  14. projects/ui/qwen-code/packages/core/src/services/loopDetectionService.ts +420 -0
  15. projects/ui/qwen-code/packages/core/src/services/shellExecutionService.test.ts +750 -0
  16. projects/ui/qwen-code/packages/core/src/services/shellExecutionService.ts +460 -0
  17. projects/ui/qwen-code/packages/core/src/telemetry/constants.ts +35 -0
  18. projects/ui/qwen-code/packages/core/src/telemetry/file-exporters.ts +89 -0
  19. projects/ui/qwen-code/packages/core/src/telemetry/index.ts +53 -0
  20. projects/ui/qwen-code/packages/core/src/telemetry/integration.test.circular.ts +111 -0
projects/ui/qwen-code/packages/core/src/qwen/qwenOAuth2.test.ts ADDED
@@ -0,0 +1,2277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import { EventEmitter } from 'events';
9
+ import { type ChildProcess } from 'child_process';
10
+ import type { Config } from '../config/config.js';
11
+ import {
12
+ generateCodeChallenge,
13
+ generateCodeVerifier,
14
+ generatePKCEPair,
15
+ isDeviceAuthorizationSuccess,
16
+ isDeviceTokenPending,
17
+ isDeviceTokenSuccess,
18
+ isErrorResponse,
19
+ QwenOAuth2Client,
20
+ type DeviceAuthorizationResponse,
21
+ type DeviceTokenResponse,
22
+ type ErrorData,
23
+ type QwenCredentials,
24
+ } from './qwenOAuth2.js';
25
+ import {
26
+ SharedTokenManager,
27
+ TokenManagerError,
28
+ TokenError,
29
+ } from './sharedTokenManager.js';
30
+
31
+ interface MockSharedTokenManager {
32
+ getValidCredentials(qwenClient: QwenOAuth2Client): Promise<QwenCredentials>;
33
+ getCurrentCredentials(): QwenCredentials | null;
34
+ clearCache(): void;
35
+ }
36
+
37
+ // Mock SharedTokenManager
38
+ vi.mock('./sharedTokenManager.js', () => ({
39
+ SharedTokenManager: class {
40
+ private static instance: MockSharedTokenManager | null = null;
41
+
42
+ static getInstance() {
43
+ if (!this.instance) {
44
+ this.instance = new this();
45
+ }
46
+ return this.instance;
47
+ }
48
+
49
+ async getValidCredentials(
50
+ qwenClient: QwenOAuth2Client,
51
+ ): Promise<QwenCredentials> {
52
+ // Try to get credentials from the client first
53
+ const clientCredentials = qwenClient.getCredentials();
54
+ if (clientCredentials && clientCredentials.access_token) {
55
+ return clientCredentials;
56
+ }
57
+
58
+ // Fall back to default mock credentials if client has none
59
+ return {
60
+ access_token: 'new-access-token',
61
+ refresh_token: 'valid-refresh-token',
62
+ resource_url: undefined,
63
+ token_type: 'Bearer',
64
+ expiry_date: Date.now() + 3600000,
65
+ };
66
+ }
67
+
68
+ getCurrentCredentials(): QwenCredentials | null {
69
+ // Return null to let the client manage its own credentials
70
+ return null;
71
+ }
72
+
73
+ clearCache(): void {
74
+ // Do nothing in mock
75
+ }
76
+ },
77
+ TokenManagerError: class extends Error {
78
+ constructor(message: string) {
79
+ super(message);
80
+ this.name = 'TokenManagerError';
81
+ }
82
+ },
83
+ TokenError: {
84
+ REFRESH_FAILED: 'REFRESH_FAILED',
85
+ NO_REFRESH_TOKEN: 'NO_REFRESH_TOKEN',
86
+ LOCK_TIMEOUT: 'LOCK_TIMEOUT',
87
+ FILE_ACCESS_ERROR: 'FILE_ACCESS_ERROR',
88
+ NETWORK_ERROR: 'NETWORK_ERROR',
89
+ },
90
+ }));
91
+
92
+ // Mock qrcode-terminal
93
+ vi.mock('qrcode-terminal', () => ({
94
+ default: {
95
+ generate: vi.fn(),
96
+ },
97
+ }));
98
+
99
+ // Mock open
100
+ vi.mock('open', () => ({
101
+ default: vi.fn(),
102
+ }));
103
+
104
+ // Mock process.stdout.write
105
+ vi.mock('process', () => ({
106
+ stdout: {
107
+ write: vi.fn(),
108
+ },
109
+ }));
110
+
111
+ // Mock file system operations
112
+ vi.mock('node:fs', () => ({
113
+ promises: {
114
+ readFile: vi.fn(),
115
+ writeFile: vi.fn(),
116
+ unlink: vi.fn(),
117
+ mkdir: vi.fn().mockResolvedValue(undefined),
118
+ },
119
+ }));
120
+
121
+ describe('PKCE Code Generation', () => {
122
+ describe('generateCodeVerifier', () => {
123
+ it('should generate a code verifier with correct length', () => {
124
+ const codeVerifier = generateCodeVerifier();
125
+ expect(codeVerifier).toMatch(/^[A-Za-z0-9_-]{43}$/);
126
+ });
127
+
128
+ it('should generate different verifiers on subsequent calls', () => {
129
+ const verifier1 = generateCodeVerifier();
130
+ const verifier2 = generateCodeVerifier();
131
+ expect(verifier1).not.toBe(verifier2);
132
+ });
133
+ });
134
+
135
+ describe('generateCodeChallenge', () => {
136
+ it('should generate code challenge from verifier', () => {
137
+ const verifier = 'test-verifier-1234567890abcdefghijklmnopqrst';
138
+ const challenge = generateCodeChallenge(verifier);
139
+
140
+ // Should be base64url encoded
141
+ expect(challenge).toMatch(/^[A-Za-z0-9_-]+$/);
142
+ expect(challenge).not.toBe(verifier);
143
+ });
144
+ });
145
+
146
+ describe('generatePKCEPair', () => {
147
+ it('should generate valid PKCE pair', () => {
148
+ const { code_verifier, code_challenge } = generatePKCEPair();
149
+
150
+ expect(code_verifier).toMatch(/^[A-Za-z0-9_-]{43}$/);
151
+ expect(code_challenge).toMatch(/^[A-Za-z0-9_-]+$/);
152
+ expect(code_verifier).not.toBe(code_challenge);
153
+ });
154
+ });
155
+ });
156
+
157
+ describe('Type Guards', () => {
158
+ describe('isDeviceAuthorizationSuccess', () => {
159
+ it('should return true for successful authorization response', () => {
160
+ const expectedBaseUrl = process.env['DEBUG']
161
+ ? 'https://pre4-chat.qwen.ai'
162
+ : 'https://chat.qwen.ai';
163
+
164
+ const successResponse: DeviceAuthorizationResponse = {
165
+ device_code: 'test-device-code',
166
+ user_code: 'TEST123',
167
+ verification_uri: `${expectedBaseUrl}/device`,
168
+ verification_uri_complete: `${expectedBaseUrl}/device?code=TEST123`,
169
+ expires_in: 1800,
170
+ };
171
+
172
+ expect(isDeviceAuthorizationSuccess(successResponse)).toBe(true);
173
+ });
174
+
175
+ it('should return false for error response', () => {
176
+ const errorResponse: DeviceAuthorizationResponse = {
177
+ error: 'INVALID_REQUEST',
178
+ error_description: 'The request parameters are invalid',
179
+ };
180
+
181
+ expect(isDeviceAuthorizationSuccess(errorResponse)).toBe(false);
182
+ });
183
+ });
184
+
185
+ describe('isDeviceTokenPending', () => {
186
+ it('should return true for pending response', () => {
187
+ const pendingResponse: DeviceTokenResponse = {
188
+ status: 'pending',
189
+ };
190
+
191
+ expect(isDeviceTokenPending(pendingResponse)).toBe(true);
192
+ });
193
+
194
+ it('should return false for success response', () => {
195
+ const successResponse: DeviceTokenResponse = {
196
+ access_token: 'valid-access-token',
197
+ refresh_token: 'valid-refresh-token',
198
+ token_type: 'Bearer',
199
+ expires_in: 3600,
200
+ scope: 'openid profile email model.completion',
201
+ };
202
+
203
+ expect(isDeviceTokenPending(successResponse)).toBe(false);
204
+ });
205
+
206
+ it('should return false for error response', () => {
207
+ const errorResponse: DeviceTokenResponse = {
208
+ error: 'ACCESS_DENIED',
209
+ error_description: 'User denied the authorization request',
210
+ };
211
+
212
+ expect(isDeviceTokenPending(errorResponse)).toBe(false);
213
+ });
214
+ });
215
+
216
+ describe('isDeviceTokenSuccess', () => {
217
+ it('should return true for successful token response', () => {
218
+ const successResponse: DeviceTokenResponse = {
219
+ access_token: 'valid-access-token',
220
+ refresh_token: 'valid-refresh-token',
221
+ token_type: 'Bearer',
222
+ expires_in: 3600,
223
+ scope: 'openid profile email model.completion',
224
+ };
225
+
226
+ expect(isDeviceTokenSuccess(successResponse)).toBe(true);
227
+ });
228
+
229
+ it('should return false for pending response', () => {
230
+ const pendingResponse: DeviceTokenResponse = {
231
+ status: 'pending',
232
+ };
233
+
234
+ expect(isDeviceTokenSuccess(pendingResponse)).toBe(false);
235
+ });
236
+
237
+ it('should return false for error response', () => {
238
+ const errorResponse: DeviceTokenResponse = {
239
+ error: 'ACCESS_DENIED',
240
+ error_description: 'User denied the authorization request',
241
+ };
242
+
243
+ expect(isDeviceTokenSuccess(errorResponse)).toBe(false);
244
+ });
245
+
246
+ it('should return false for null access token', () => {
247
+ const nullTokenResponse: DeviceTokenResponse = {
248
+ access_token: null,
249
+ token_type: 'Bearer',
250
+ expires_in: 3600,
251
+ };
252
+
253
+ expect(isDeviceTokenSuccess(nullTokenResponse)).toBe(false);
254
+ });
255
+
256
+ it('should return false for empty access token', () => {
257
+ const emptyTokenResponse: DeviceTokenResponse = {
258
+ access_token: '',
259
+ token_type: 'Bearer',
260
+ expires_in: 3600,
261
+ };
262
+
263
+ expect(isDeviceTokenSuccess(emptyTokenResponse)).toBe(false);
264
+ });
265
+ });
266
+
267
+ describe('isErrorResponse', () => {
268
+ it('should return true for error responses', () => {
269
+ const errorResponse: ErrorData = {
270
+ error: 'INVALID_REQUEST',
271
+ error_description: 'The request parameters are invalid',
272
+ };
273
+
274
+ expect(isErrorResponse(errorResponse)).toBe(true);
275
+ });
276
+
277
+ it('should return false for successful responses', () => {
278
+ const successResponse: DeviceAuthorizationResponse = {
279
+ device_code: 'test-device-code',
280
+ user_code: 'TEST123',
281
+ verification_uri: 'https://chat.qwen.ai/device',
282
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
283
+ expires_in: 1800,
284
+ };
285
+
286
+ expect(isErrorResponse(successResponse)).toBe(false);
287
+ });
288
+ });
289
+ });
290
+
291
+ describe('QwenOAuth2Client', () => {
292
+ let client: QwenOAuth2Client;
293
+ let originalFetch: typeof global.fetch;
294
+
295
+ beforeEach(() => {
296
+ // Create client instance
297
+ client = new QwenOAuth2Client();
298
+
299
+ // Mock fetch
300
+ originalFetch = global.fetch;
301
+ global.fetch = vi.fn();
302
+ });
303
+
304
+ afterEach(() => {
305
+ global.fetch = originalFetch;
306
+ vi.clearAllMocks();
307
+ });
308
+
309
+ describe('requestDeviceAuthorization', () => {
310
+ it('should successfully request device authorization', async () => {
311
+ const mockResponse = {
312
+ ok: true,
313
+ json: async () => ({
314
+ device_code: 'test-device-code',
315
+ user_code: 'TEST123',
316
+ verification_uri: 'https://chat.qwen.ai/device',
317
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
318
+ expires_in: 1800,
319
+ }),
320
+ };
321
+
322
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
323
+
324
+ const result = await client.requestDeviceAuthorization({
325
+ scope: 'openid profile email model.completion',
326
+ code_challenge: 'test-challenge',
327
+ code_challenge_method: 'S256',
328
+ });
329
+
330
+ expect(result).toEqual({
331
+ device_code: 'test-device-code',
332
+ user_code: 'TEST123',
333
+ verification_uri: 'https://chat.qwen.ai/device',
334
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
335
+ expires_in: 1800,
336
+ });
337
+ });
338
+
339
+ it('should handle error response', async () => {
340
+ const mockResponse = {
341
+ ok: true,
342
+ json: async () => ({
343
+ error: 'INVALID_REQUEST',
344
+ error_description: 'The request parameters are invalid',
345
+ }),
346
+ };
347
+
348
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
349
+
350
+ await expect(
351
+ client.requestDeviceAuthorization({
352
+ scope: 'openid profile email model.completion',
353
+ code_challenge: 'test-challenge',
354
+ code_challenge_method: 'S256',
355
+ }),
356
+ ).rejects.toThrow(
357
+ 'Device authorization failed: INVALID_REQUEST - The request parameters are invalid',
358
+ );
359
+ });
360
+ });
361
+
362
+ describe('refreshAccessToken', () => {
363
+ beforeEach(() => {
364
+ // Set up client with credentials
365
+ client.setCredentials({
366
+ access_token: 'old-token',
367
+ refresh_token: 'test-refresh-token',
368
+ token_type: 'Bearer',
369
+ });
370
+ });
371
+
372
+ it('should successfully refresh access token', async () => {
373
+ const mockResponse = {
374
+ ok: true,
375
+ json: async () => ({
376
+ access_token: 'new-access-token',
377
+ token_type: 'Bearer',
378
+ expires_in: 3600,
379
+ resource_url: 'https://new-endpoint.com',
380
+ }),
381
+ };
382
+
383
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
384
+
385
+ const result = await client.refreshAccessToken();
386
+
387
+ expect(result).toEqual({
388
+ access_token: 'new-access-token',
389
+ token_type: 'Bearer',
390
+ expires_in: 3600,
391
+ resource_url: 'https://new-endpoint.com',
392
+ });
393
+
394
+ // Verify credentials were updated
395
+ const credentials = client.getCredentials();
396
+ expect(credentials.access_token).toBe('new-access-token');
397
+ });
398
+
399
+ it('should handle refresh error', async () => {
400
+ const mockResponse = {
401
+ ok: true,
402
+ json: async () => ({
403
+ error: 'INVALID_GRANT',
404
+ error_description: 'The refresh token is invalid',
405
+ }),
406
+ };
407
+
408
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
409
+
410
+ await expect(client.refreshAccessToken()).rejects.toThrow(
411
+ 'Token refresh failed: INVALID_GRANT - The refresh token is invalid',
412
+ );
413
+ });
414
+
415
+ it('should successfully refresh access token and update credentials', async () => {
416
+ // Clear any previous calls
417
+ vi.clearAllMocks();
418
+
419
+ const mockResponse = {
420
+ ok: true,
421
+ json: async () => ({
422
+ access_token: 'new-access-token',
423
+ token_type: 'Bearer',
424
+ expires_in: 3600,
425
+ resource_url: 'https://new-endpoint.com',
426
+ }),
427
+ };
428
+
429
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
430
+
431
+ const result = await client.refreshAccessToken();
432
+
433
+ // Verify the response
434
+ expect(result).toMatchObject({
435
+ access_token: 'new-access-token',
436
+ token_type: 'Bearer',
437
+ expires_in: 3600,
438
+ resource_url: 'https://new-endpoint.com',
439
+ });
440
+
441
+ // Verify credentials were updated
442
+ const credentials = client.getCredentials();
443
+ expect(credentials).toMatchObject({
444
+ access_token: 'new-access-token',
445
+ token_type: 'Bearer',
446
+ refresh_token: 'test-refresh-token', // Should preserve existing refresh token
447
+ resource_url: 'https://new-endpoint.com',
448
+ });
449
+ expect(credentials.expiry_date).toBeDefined();
450
+ });
451
+
452
+ it('should use new refresh token if provided in response', async () => {
453
+ // Clear any previous calls
454
+ vi.clearAllMocks();
455
+
456
+ const mockResponse = {
457
+ ok: true,
458
+ json: async () => ({
459
+ access_token: 'new-access-token',
460
+ token_type: 'Bearer',
461
+ expires_in: 3600,
462
+ refresh_token: 'new-refresh-token', // New refresh token provided
463
+ resource_url: 'https://new-endpoint.com',
464
+ }),
465
+ };
466
+
467
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
468
+
469
+ await client.refreshAccessToken();
470
+
471
+ // Verify the credentials contain the new refresh token
472
+ const credentials = client.getCredentials();
473
+ expect(credentials.refresh_token).toBe('new-refresh-token');
474
+ });
475
+ });
476
+
477
+ describe('getAccessToken', () => {
478
+ it('should return access token if valid and not expired', async () => {
479
+ // Set valid credentials
480
+ client.setCredentials({
481
+ access_token: 'valid-token',
482
+ expiry_date: Date.now() + 60 * 60 * 1000, // 1 hour from now
483
+ });
484
+
485
+ const result = await client.getAccessToken();
486
+ expect(result.token).toBe('valid-token');
487
+ });
488
+
489
+ it('should refresh token if access token is expired', async () => {
490
+ // Set expired credentials with refresh token
491
+ client.setCredentials({
492
+ access_token: 'expired-token',
493
+ refresh_token: 'valid-refresh-token',
494
+ expiry_date: Date.now() - 1000, // 1 second ago
495
+ });
496
+
497
+ // Override the client's SharedTokenManager instance directly
498
+ (
499
+ client as unknown as {
500
+ sharedManager: {
501
+ getValidCredentials: () => Promise<QwenCredentials>;
502
+ };
503
+ }
504
+ ).sharedManager = {
505
+ getValidCredentials: vi.fn().mockResolvedValue({
506
+ access_token: 'new-access-token',
507
+ refresh_token: 'valid-refresh-token',
508
+ token_type: 'Bearer',
509
+ expiry_date: Date.now() + 3600000,
510
+ }),
511
+ };
512
+
513
+ const result = await client.getAccessToken();
514
+ expect(result.token).toBe('new-access-token');
515
+ });
516
+
517
+ it('should return undefined if no access token and no refresh token', async () => {
518
+ client.setCredentials({});
519
+
520
+ // Override the client's SharedTokenManager instance directly
521
+ (
522
+ client as unknown as {
523
+ sharedManager: {
524
+ getValidCredentials: () => Promise<QwenCredentials>;
525
+ };
526
+ }
527
+ ).sharedManager = {
528
+ getValidCredentials: vi
529
+ .fn()
530
+ .mockRejectedValue(new Error('No credentials available')),
531
+ };
532
+
533
+ const result = await client.getAccessToken();
534
+ expect(result.token).toBeUndefined();
535
+ });
536
+ });
537
+
538
+ describe('pollDeviceToken', () => {
539
+ it('should successfully poll for device token', async () => {
540
+ const mockResponse = {
541
+ ok: true,
542
+ json: async () => ({
543
+ access_token: 'new-access-token',
544
+ refresh_token: 'new-refresh-token',
545
+ token_type: 'Bearer',
546
+ expires_in: 3600,
547
+ scope: 'openid profile email model.completion',
548
+ }),
549
+ };
550
+
551
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
552
+
553
+ const result = await client.pollDeviceToken({
554
+ device_code: 'test-device-code',
555
+ code_verifier: 'test-code-verifier',
556
+ });
557
+
558
+ expect(result).toEqual({
559
+ access_token: 'new-access-token',
560
+ refresh_token: 'new-refresh-token',
561
+ token_type: 'Bearer',
562
+ expires_in: 3600,
563
+ scope: 'openid profile email model.completion',
564
+ });
565
+ });
566
+
567
+ it('should return pending status when authorization is pending', async () => {
568
+ const mockResponse = {
569
+ ok: true,
570
+ json: async () => ({
571
+ status: 'pending',
572
+ }),
573
+ };
574
+
575
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
576
+
577
+ const result = await client.pollDeviceToken({
578
+ device_code: 'test-device-code',
579
+ code_verifier: 'test-code-verifier',
580
+ });
581
+
582
+ expect(result).toEqual({
583
+ status: 'pending',
584
+ });
585
+ });
586
+
587
+ it('should handle HTTP error responses', async () => {
588
+ const mockResponse = {
589
+ ok: false,
590
+ status: 400,
591
+ statusText: 'Bad Request',
592
+ text: async () => 'Invalid device code',
593
+ };
594
+
595
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
596
+
597
+ await expect(
598
+ client.pollDeviceToken({
599
+ device_code: 'invalid-device-code',
600
+ code_verifier: 'test-code-verifier',
601
+ }),
602
+ ).rejects.toThrow('Device token poll failed: 400 Bad Request');
603
+ });
604
+
605
+ it('should include status code in error for better handling', async () => {
606
+ const mockResponse = {
607
+ ok: false,
608
+ status: 429,
609
+ statusText: 'Too Many Requests',
610
+ text: async () => 'Rate limited',
611
+ };
612
+
613
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
614
+
615
+ try {
616
+ await client.pollDeviceToken({
617
+ device_code: 'test-device-code',
618
+ code_verifier: 'test-code-verifier',
619
+ });
620
+ } catch (error) {
621
+ expect((error as Error & { status?: number }).status).toBe(429);
622
+ }
623
+ });
624
+
625
+ it('should handle authorization_pending with HTTP 400 according to RFC 8628', async () => {
626
+ const mockResponse = {
627
+ ok: false,
628
+ status: 400,
629
+ statusText: 'Bad Request',
630
+ json: async () => ({
631
+ error: 'authorization_pending',
632
+ error_description: 'The authorization request is still pending',
633
+ }),
634
+ };
635
+
636
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
637
+
638
+ const result = await client.pollDeviceToken({
639
+ device_code: 'test-device-code',
640
+ code_verifier: 'test-code-verifier',
641
+ });
642
+
643
+ expect(result).toEqual({
644
+ status: 'pending',
645
+ });
646
+ });
647
+
648
+ it('should handle slow_down with HTTP 429 according to RFC 8628', async () => {
649
+ const mockResponse = {
650
+ ok: false,
651
+ status: 429,
652
+ statusText: 'Too Many Requests',
653
+ json: async () => ({
654
+ error: 'slow_down',
655
+ error_description: 'The client is polling too frequently',
656
+ }),
657
+ };
658
+
659
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
660
+
661
+ const result = await client.pollDeviceToken({
662
+ device_code: 'test-device-code',
663
+ code_verifier: 'test-code-verifier',
664
+ });
665
+
666
+ expect(result).toEqual({
667
+ status: 'pending',
668
+ slowDown: true,
669
+ });
670
+ });
671
+ });
672
+
673
+ describe('refreshAccessToken error handling', () => {
674
+ beforeEach(() => {
675
+ client.setCredentials({
676
+ access_token: 'old-token',
677
+ refresh_token: 'test-refresh-token',
678
+ token_type: 'Bearer',
679
+ });
680
+ });
681
+
682
+ it('should throw error if no refresh token available', async () => {
683
+ client.setCredentials({ access_token: 'token' });
684
+
685
+ await expect(client.refreshAccessToken()).rejects.toThrow(
686
+ 'No refresh token available',
687
+ );
688
+ });
689
+
690
+ it('should handle 400 status as expired refresh token', async () => {
691
+ const mockResponse = {
692
+ ok: false,
693
+ status: 400,
694
+ statusText: 'Bad Request',
695
+ text: async () => 'Refresh token expired',
696
+ };
697
+
698
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
699
+
700
+ await expect(client.refreshAccessToken()).rejects.toThrow(
701
+ "Refresh token expired or invalid. Please use '/auth' to re-authenticate.",
702
+ );
703
+ });
704
+
705
+ it('should handle other HTTP error statuses', async () => {
706
+ const mockResponse = {
707
+ ok: false,
708
+ status: 500,
709
+ statusText: 'Internal Server Error',
710
+ text: async () => 'Server error',
711
+ };
712
+
713
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
714
+
715
+ await expect(client.refreshAccessToken()).rejects.toThrow(
716
+ 'Token refresh failed: 500 Internal Server Error',
717
+ );
718
+ });
719
+ });
720
+
721
+ describe('credentials management', () => {
722
+ it('should set and get credentials correctly', () => {
723
+ const credentials = {
724
+ access_token: 'test-token',
725
+ refresh_token: 'test-refresh',
726
+ token_type: 'Bearer',
727
+ expiry_date: Date.now() + 3600000,
728
+ };
729
+
730
+ client.setCredentials(credentials);
731
+ expect(client.getCredentials()).toEqual(credentials);
732
+ });
733
+
734
+ it('should handle empty credentials', () => {
735
+ client.setCredentials({});
736
+ expect(client.getCredentials()).toEqual({});
737
+ });
738
+ });
739
+ });
740
+
741
+ describe('getQwenOAuthClient', () => {
742
+ let mockConfig: Config;
743
+ let originalFetch: typeof global.fetch;
744
+
745
+ beforeEach(() => {
746
+ mockConfig = {
747
+ isBrowserLaunchSuppressed: vi.fn().mockReturnValue(false),
748
+ } as unknown as Config;
749
+
750
+ originalFetch = global.fetch;
751
+ global.fetch = vi.fn();
752
+ });
753
+
754
+ afterEach(() => {
755
+ global.fetch = originalFetch;
756
+ vi.clearAllMocks();
757
+ });
758
+
759
+ it('should load cached credentials if available', async () => {
760
+ const fs = await import('node:fs');
761
+ const mockCredentials = {
762
+ access_token: 'cached-token',
763
+ refresh_token: 'cached-refresh',
764
+ token_type: 'Bearer',
765
+ expiry_date: Date.now() + 3600000,
766
+ };
767
+
768
+ vi.mocked(fs.promises.readFile).mockResolvedValue(
769
+ JSON.stringify(mockCredentials),
770
+ );
771
+
772
+ // Mock SharedTokenManager to use cached credentials
773
+ const mockTokenManager = {
774
+ getValidCredentials: vi.fn().mockResolvedValue(mockCredentials),
775
+ };
776
+
777
+ const originalGetInstance = SharedTokenManager.getInstance;
778
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
779
+
780
+ const client = await import('./qwenOAuth2.js').then((module) =>
781
+ module.getQwenOAuthClient(mockConfig),
782
+ );
783
+
784
+ expect(client).toBeInstanceOf(Object);
785
+ expect(mockTokenManager.getValidCredentials).toHaveBeenCalled();
786
+
787
+ SharedTokenManager.getInstance = originalGetInstance;
788
+ });
789
+
790
+ it('should handle cached credentials refresh failure', async () => {
791
+ const fs = await import('node:fs');
792
+ const mockCredentials = {
793
+ access_token: 'cached-token',
794
+ refresh_token: 'expired-refresh',
795
+ token_type: 'Bearer',
796
+ expiry_date: Date.now() + 3600000, // Valid expiry time so loadCachedQwenCredentials returns true
797
+ };
798
+
799
+ vi.mocked(fs.promises.readFile).mockResolvedValue(
800
+ JSON.stringify(mockCredentials),
801
+ );
802
+
803
+ // Mock SharedTokenManager to fail with a specific error
804
+ const mockTokenManager = {
805
+ getValidCredentials: vi
806
+ .fn()
807
+ .mockRejectedValue(new Error('Token refresh failed')),
808
+ };
809
+
810
+ const originalGetInstance = SharedTokenManager.getInstance;
811
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
812
+
813
+ // Mock device flow to also fail
814
+ const mockAuthResponse = {
815
+ ok: true,
816
+ json: async () => ({
817
+ error: 'invalid_request',
818
+ error_description: 'Invalid request parameters',
819
+ }),
820
+ };
821
+ vi.mocked(global.fetch).mockResolvedValue(mockAuthResponse as Response);
822
+
823
+ // The function should handle the invalid cached credentials and throw the expected error
824
+ await expect(
825
+ import('./qwenOAuth2.js').then((module) =>
826
+ module.getQwenOAuthClient(mockConfig),
827
+ ),
828
+ ).rejects.toThrow('Qwen OAuth authentication failed');
829
+
830
+ SharedTokenManager.getInstance = originalGetInstance;
831
+ });
832
+ });
833
+
834
+ describe('clearQwenCredentials', () => {
835
+ it('should successfully clear credentials file', async () => {
836
+ const { promises: fs } = await import('node:fs');
837
+ const { clearQwenCredentials } = await import('./qwenOAuth2.js');
838
+
839
+ vi.mocked(fs.unlink).mockResolvedValue(undefined);
840
+
841
+ await expect(clearQwenCredentials()).resolves.not.toThrow();
842
+ expect(fs.unlink).toHaveBeenCalled();
843
+ });
844
+
845
+ it('should handle file not found error gracefully', async () => {
846
+ const { promises: fs } = await import('node:fs');
847
+ const { clearQwenCredentials } = await import('./qwenOAuth2.js');
848
+
849
+ const notFoundError = new Error('File not found');
850
+ (notFoundError as Error & { code: string }).code = 'ENOENT';
851
+ vi.mocked(fs.unlink).mockRejectedValue(notFoundError);
852
+
853
+ await expect(clearQwenCredentials()).resolves.not.toThrow();
854
+ });
855
+
856
+ it('should handle other file system errors gracefully', async () => {
857
+ const { promises: fs } = await import('node:fs');
858
+ const { clearQwenCredentials } = await import('./qwenOAuth2.js');
859
+
860
+ const permissionError = new Error('Permission denied');
861
+ vi.mocked(fs.unlink).mockRejectedValue(permissionError);
862
+
863
+ // Should not throw but may log warning
864
+ await expect(clearQwenCredentials()).resolves.not.toThrow();
865
+ });
866
+ });
867
+
868
+ describe('QwenOAuth2Client - Additional Error Scenarios', () => {
869
+ let client: QwenOAuth2Client;
870
+ let originalFetch: typeof global.fetch;
871
+
872
+ beforeEach(() => {
873
+ client = new QwenOAuth2Client();
874
+ originalFetch = global.fetch;
875
+ global.fetch = vi.fn();
876
+ });
877
+
878
+ afterEach(() => {
879
+ global.fetch = originalFetch;
880
+ vi.clearAllMocks();
881
+ });
882
+
883
+ describe('requestDeviceAuthorization HTTP errors', () => {
884
+ it('should handle HTTP error response with non-ok status', async () => {
885
+ const mockResponse = {
886
+ ok: false,
887
+ status: 500,
888
+ statusText: 'Internal Server Error',
889
+ text: async () => 'Server error occurred',
890
+ };
891
+
892
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
893
+
894
+ await expect(
895
+ client.requestDeviceAuthorization({
896
+ scope: 'openid profile email model.completion',
897
+ code_challenge: 'test-challenge',
898
+ code_challenge_method: 'S256',
899
+ }),
900
+ ).rejects.toThrow(
901
+ 'Device authorization failed: 500 Internal Server Error. Response: Server error occurred',
902
+ );
903
+ });
904
+ });
905
+
906
+ describe('isTokenValid edge cases', () => {
907
+ it('should return false when expiry_date is undefined', () => {
908
+ client.setCredentials({
909
+ access_token: 'token',
910
+ // expiry_date is undefined
911
+ });
912
+
913
+ // Access private method for testing
914
+ const isValid = (
915
+ client as unknown as { isTokenValid(): boolean }
916
+ ).isTokenValid();
917
+ expect(isValid).toBe(false);
918
+ });
919
+ });
920
+ });
921
+
922
+ describe('getQwenOAuthClient - Enhanced Error Scenarios', () => {
923
+ let mockConfig: Config;
924
+ let originalFetch: typeof global.fetch;
925
+
926
+ beforeEach(() => {
927
+ mockConfig = {
928
+ isBrowserLaunchSuppressed: vi.fn().mockReturnValue(false),
929
+ } as unknown as Config;
930
+
931
+ originalFetch = global.fetch;
932
+ global.fetch = vi.fn();
933
+ });
934
+
935
+ afterEach(() => {
936
+ global.fetch = originalFetch;
937
+ vi.clearAllMocks();
938
+ });
939
+
940
+ it('should handle generic refresh token errors', async () => {
941
+ const { promises: fs } = await import('node:fs');
942
+ const mockCredentials = {
943
+ access_token: 'cached-token',
944
+ refresh_token: 'some-refresh-token',
945
+ token_type: 'Bearer',
946
+ expiry_date: Date.now() + 3600000,
947
+ };
948
+
949
+ vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockCredentials));
950
+
951
+ // Mock SharedTokenManager to fail
952
+ const mockTokenManager = {
953
+ getValidCredentials: vi
954
+ .fn()
955
+ .mockRejectedValue(new Error('Refresh failed')),
956
+ };
957
+
958
+ const originalGetInstance = SharedTokenManager.getInstance;
959
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
960
+
961
+ // Mock device flow to also fail
962
+ const mockAuthResponse = {
963
+ ok: true,
964
+ json: async () => ({
965
+ error: 'invalid_request',
966
+ error_description: 'Invalid request parameters',
967
+ }),
968
+ };
969
+ vi.mocked(global.fetch).mockResolvedValue(mockAuthResponse as Response);
970
+
971
+ await expect(
972
+ import('./qwenOAuth2.js').then((module) =>
973
+ module.getQwenOAuthClient(mockConfig),
974
+ ),
975
+ ).rejects.toThrow('Qwen OAuth authentication failed');
976
+
977
+ SharedTokenManager.getInstance = originalGetInstance;
978
+ });
979
+
980
+ it('should handle different authentication failure reasons - timeout', async () => {
981
+ const { promises: fs } = await import('node:fs');
982
+ vi.mocked(fs.readFile).mockRejectedValue(
983
+ new Error('No cached credentials'),
984
+ );
985
+
986
+ // Mock SharedTokenManager to fail
987
+ const mockTokenManager = {
988
+ getValidCredentials: vi
989
+ .fn()
990
+ .mockRejectedValue(new Error('No credentials')),
991
+ };
992
+
993
+ const originalGetInstance = SharedTokenManager.getInstance;
994
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
995
+
996
+ // Mock device authorization to succeed but polling to timeout
997
+ const mockAuthResponse = {
998
+ ok: true,
999
+ json: async () => ({
1000
+ device_code: 'test-device-code',
1001
+ user_code: 'TEST123',
1002
+ verification_uri: 'https://chat.qwen.ai/device',
1003
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1004
+ expires_in: 0.1, // Very short timeout for testing
1005
+ }),
1006
+ };
1007
+
1008
+ const mockPendingResponse = {
1009
+ ok: true,
1010
+ json: async () => ({
1011
+ status: 'pending',
1012
+ }),
1013
+ };
1014
+
1015
+ global.fetch = vi
1016
+ .fn()
1017
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1018
+ .mockResolvedValue(mockPendingResponse as Response);
1019
+
1020
+ await expect(
1021
+ import('./qwenOAuth2.js').then((module) =>
1022
+ module.getQwenOAuthClient(mockConfig),
1023
+ ),
1024
+ ).rejects.toThrow('Qwen OAuth authentication timed out');
1025
+
1026
+ SharedTokenManager.getInstance = originalGetInstance;
1027
+ });
1028
+
1029
+ it('should handle authentication failure reason - rate limit', async () => {
1030
+ const { promises: fs } = await import('node:fs');
1031
+ vi.mocked(fs.readFile).mockRejectedValue(
1032
+ new Error('No cached credentials'),
1033
+ );
1034
+
1035
+ // Mock SharedTokenManager to fail
1036
+ const mockTokenManager = {
1037
+ getValidCredentials: vi
1038
+ .fn()
1039
+ .mockRejectedValue(new Error('No credentials')),
1040
+ };
1041
+
1042
+ const originalGetInstance = SharedTokenManager.getInstance;
1043
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
1044
+
1045
+ // Mock device authorization to succeed but polling to get rate limited
1046
+ const mockAuthResponse = {
1047
+ ok: true,
1048
+ json: async () => ({
1049
+ device_code: 'test-device-code',
1050
+ user_code: 'TEST123',
1051
+ verification_uri: 'https://chat.qwen.ai/device',
1052
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1053
+ expires_in: 1800,
1054
+ }),
1055
+ };
1056
+
1057
+ const mockRateLimitResponse = {
1058
+ ok: false,
1059
+ status: 429,
1060
+ statusText: 'Too Many Requests',
1061
+ text: async () => 'Rate limited',
1062
+ };
1063
+
1064
+ global.fetch = vi
1065
+ .fn()
1066
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1067
+ .mockResolvedValue(mockRateLimitResponse as Response);
1068
+
1069
+ await expect(
1070
+ import('./qwenOAuth2.js').then((module) =>
1071
+ module.getQwenOAuthClient(mockConfig),
1072
+ ),
1073
+ ).rejects.toThrow(
1074
+ 'Too many request for Qwen OAuth authentication, please try again later.',
1075
+ );
1076
+
1077
+ SharedTokenManager.getInstance = originalGetInstance;
1078
+ });
1079
+
1080
+ it('should handle authentication failure reason - error', async () => {
1081
+ const { promises: fs } = await import('node:fs');
1082
+ vi.mocked(fs.readFile).mockRejectedValue(
1083
+ new Error('No cached credentials'),
1084
+ );
1085
+
1086
+ // Mock SharedTokenManager to fail
1087
+ const mockTokenManager = {
1088
+ getValidCredentials: vi
1089
+ .fn()
1090
+ .mockRejectedValue(new Error('No credentials')),
1091
+ };
1092
+
1093
+ const originalGetInstance = SharedTokenManager.getInstance;
1094
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
1095
+
1096
+ // Mock device authorization to fail
1097
+ const mockAuthResponse = {
1098
+ ok: true,
1099
+ json: async () => ({
1100
+ error: 'invalid_request',
1101
+ error_description: 'Invalid request parameters',
1102
+ }),
1103
+ };
1104
+
1105
+ global.fetch = vi.fn().mockResolvedValue(mockAuthResponse as Response);
1106
+
1107
+ await expect(
1108
+ import('./qwenOAuth2.js').then((module) =>
1109
+ module.getQwenOAuthClient(mockConfig),
1110
+ ),
1111
+ ).rejects.toThrow('Qwen OAuth authentication failed');
1112
+
1113
+ SharedTokenManager.getInstance = originalGetInstance;
1114
+ });
1115
+ });
1116
+
1117
+ describe('authWithQwenDeviceFlow - Comprehensive Testing', () => {
1118
+ let mockConfig: Config;
1119
+ let originalFetch: typeof global.fetch;
1120
+
1121
+ beforeEach(() => {
1122
+ mockConfig = {
1123
+ isBrowserLaunchSuppressed: vi.fn().mockReturnValue(false),
1124
+ } as unknown as Config;
1125
+
1126
+ originalFetch = global.fetch;
1127
+ global.fetch = vi.fn();
1128
+
1129
+ // Mock setTimeout to avoid real delays in tests
1130
+ vi.useFakeTimers();
1131
+ });
1132
+
1133
+ afterEach(() => {
1134
+ global.fetch = originalFetch;
1135
+ vi.clearAllMocks();
1136
+ vi.useRealTimers();
1137
+ });
1138
+
1139
+ it('should handle device authorization error response', async () => {
1140
+ const { promises: fs } = await import('node:fs');
1141
+ vi.mocked(fs.readFile).mockRejectedValue(
1142
+ new Error('No cached credentials'),
1143
+ );
1144
+
1145
+ // Mock SharedTokenManager to fail
1146
+ const mockTokenManager = {
1147
+ getValidCredentials: vi
1148
+ .fn()
1149
+ .mockRejectedValue(new Error('No credentials')),
1150
+ };
1151
+
1152
+ const originalGetInstance = SharedTokenManager.getInstance;
1153
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
1154
+
1155
+ const mockAuthResponse = {
1156
+ ok: true,
1157
+ json: async () => ({
1158
+ error: 'invalid_client',
1159
+ error_description: 'Client authentication failed',
1160
+ }),
1161
+ };
1162
+
1163
+ global.fetch = vi.fn().mockResolvedValue(mockAuthResponse as Response);
1164
+
1165
+ await expect(
1166
+ import('./qwenOAuth2.js').then((module) =>
1167
+ module.getQwenOAuthClient(mockConfig),
1168
+ ),
1169
+ ).rejects.toThrow('Qwen OAuth authentication failed');
1170
+
1171
+ SharedTokenManager.getInstance = originalGetInstance;
1172
+ });
1173
+
1174
+ it('should handle successful authentication flow', async () => {
1175
+ const { promises: fs } = await import('node:fs');
1176
+ vi.mocked(fs.readFile).mockRejectedValue(
1177
+ new Error('No cached credentials'),
1178
+ );
1179
+
1180
+ const mockAuthResponse = {
1181
+ ok: true,
1182
+ json: async () => ({
1183
+ device_code: 'test-device-code',
1184
+ user_code: 'TEST123',
1185
+ verification_uri: 'https://chat.qwen.ai/device',
1186
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1187
+ expires_in: 1800,
1188
+ }),
1189
+ };
1190
+
1191
+ const mockTokenResponse = {
1192
+ ok: true,
1193
+ json: async () => ({
1194
+ access_token: 'new-access-token',
1195
+ refresh_token: 'new-refresh-token',
1196
+ token_type: 'Bearer',
1197
+ expires_in: 3600,
1198
+ scope: 'openid profile email model.completion',
1199
+ }),
1200
+ };
1201
+
1202
+ vi.mocked(global.fetch)
1203
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1204
+ .mockResolvedValue(mockTokenResponse as Response);
1205
+
1206
+ const client = await import('./qwenOAuth2.js').then((module) =>
1207
+ module.getQwenOAuthClient(mockConfig),
1208
+ );
1209
+
1210
+ expect(client).toBeInstanceOf(Object);
1211
+ });
1212
+
1213
+ it('should handle 401 error during token polling', async () => {
1214
+ const { promises: fs } = await import('node:fs');
1215
+ vi.mocked(fs.readFile).mockRejectedValue(
1216
+ new Error('No cached credentials'),
1217
+ );
1218
+
1219
+ // Mock SharedTokenManager to fail
1220
+ const mockTokenManager = {
1221
+ getValidCredentials: vi
1222
+ .fn()
1223
+ .mockRejectedValue(new Error('No credentials')),
1224
+ };
1225
+
1226
+ const originalGetInstance = SharedTokenManager.getInstance;
1227
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
1228
+
1229
+ const mockAuthResponse = {
1230
+ ok: true,
1231
+ json: async () => ({
1232
+ device_code: 'test-device-code',
1233
+ user_code: 'TEST123',
1234
+ verification_uri: 'https://chat.qwen.ai/device',
1235
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1236
+ expires_in: 1800,
1237
+ }),
1238
+ };
1239
+
1240
+ const mock401Response = {
1241
+ ok: false,
1242
+ status: 401,
1243
+ statusText: 'Unauthorized',
1244
+ text: async () => 'Device code expired',
1245
+ };
1246
+
1247
+ global.fetch = vi
1248
+ .fn()
1249
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1250
+ .mockResolvedValue(mock401Response as Response);
1251
+
1252
+ await expect(
1253
+ import('./qwenOAuth2.js').then((module) =>
1254
+ module.getQwenOAuthClient(mockConfig),
1255
+ ),
1256
+ ).rejects.toThrow('Qwen OAuth authentication failed');
1257
+
1258
+ SharedTokenManager.getInstance = originalGetInstance;
1259
+ });
1260
+
1261
+ it('should handle token polling with browser launch suppressed', async () => {
1262
+ const { promises: fs } = await import('node:fs');
1263
+ vi.mocked(fs.readFile).mockRejectedValue(
1264
+ new Error('No cached credentials'),
1265
+ );
1266
+
1267
+ // Mock SharedTokenManager to fail initially so device flow is used
1268
+ const mockTokenManager = {
1269
+ getValidCredentials: vi
1270
+ .fn()
1271
+ .mockRejectedValue(new Error('No credentials')),
1272
+ };
1273
+
1274
+ const originalGetInstance = SharedTokenManager.getInstance;
1275
+ SharedTokenManager.getInstance = vi.fn().mockReturnValue(mockTokenManager);
1276
+
1277
+ // Mock browser launch as suppressed
1278
+ mockConfig.isBrowserLaunchSuppressed = vi.fn().mockReturnValue(true);
1279
+
1280
+ const mockAuthResponse = {
1281
+ ok: true,
1282
+ json: async () => ({
1283
+ device_code: 'test-device-code',
1284
+ user_code: 'TEST123',
1285
+ verification_uri: 'https://chat.qwen.ai/device',
1286
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1287
+ expires_in: 1800,
1288
+ }),
1289
+ };
1290
+
1291
+ const mockTokenResponse = {
1292
+ ok: true,
1293
+ json: async () => ({
1294
+ access_token: 'new-access-token',
1295
+ refresh_token: 'new-refresh-token',
1296
+ token_type: 'Bearer',
1297
+ expires_in: 3600,
1298
+ scope: 'openid profile email model.completion',
1299
+ }),
1300
+ };
1301
+
1302
+ global.fetch = vi
1303
+ .fn()
1304
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1305
+ .mockResolvedValue(mockTokenResponse as Response);
1306
+
1307
+ const client = await import('./qwenOAuth2.js').then((module) =>
1308
+ module.getQwenOAuthClient(mockConfig),
1309
+ );
1310
+
1311
+ expect(client).toBeInstanceOf(Object);
1312
+ expect(mockConfig.isBrowserLaunchSuppressed).toHaveBeenCalled();
1313
+
1314
+ SharedTokenManager.getInstance = originalGetInstance;
1315
+ });
1316
+ });
1317
+
1318
+ describe('Browser Launch and Error Handling', () => {
1319
+ let mockConfig: Config;
1320
+ let originalFetch: typeof global.fetch;
1321
+
1322
+ beforeEach(() => {
1323
+ mockConfig = {
1324
+ isBrowserLaunchSuppressed: vi.fn().mockReturnValue(false),
1325
+ } as unknown as Config;
1326
+
1327
+ originalFetch = global.fetch;
1328
+ global.fetch = vi.fn();
1329
+ });
1330
+
1331
+ afterEach(() => {
1332
+ global.fetch = originalFetch;
1333
+ vi.clearAllMocks();
1334
+ });
1335
+
1336
+ it('should handle browser launch failure gracefully', async () => {
1337
+ const { promises: fs } = await import('node:fs');
1338
+ vi.mocked(fs.readFile).mockRejectedValue(
1339
+ new Error('No cached credentials'),
1340
+ );
1341
+
1342
+ // Mock open to throw error
1343
+ const open = await import('open');
1344
+ vi.mocked(open.default).mockRejectedValue(
1345
+ new Error('Browser launch failed'),
1346
+ );
1347
+
1348
+ const mockAuthResponse = {
1349
+ ok: true,
1350
+ json: async () => ({
1351
+ device_code: 'test-device-code',
1352
+ user_code: 'TEST123',
1353
+ verification_uri: 'https://chat.qwen.ai/device',
1354
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1355
+ expires_in: 1800,
1356
+ }),
1357
+ };
1358
+
1359
+ const mockTokenResponse = {
1360
+ ok: true,
1361
+ json: async () => ({
1362
+ access_token: 'new-access-token',
1363
+ refresh_token: 'new-refresh-token',
1364
+ token_type: 'Bearer',
1365
+ expires_in: 3600,
1366
+ scope: 'openid profile email model.completion',
1367
+ }),
1368
+ };
1369
+
1370
+ vi.mocked(global.fetch)
1371
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1372
+ .mockResolvedValue(mockTokenResponse as Response);
1373
+
1374
+ const client = await import('./qwenOAuth2.js').then((module) =>
1375
+ module.getQwenOAuthClient(mockConfig),
1376
+ );
1377
+
1378
+ expect(client).toBeInstanceOf(Object);
1379
+ });
1380
+
1381
+ it('should handle browser child process error gracefully', async () => {
1382
+ const { promises: fs } = await import('node:fs');
1383
+ vi.mocked(fs.readFile).mockRejectedValue(
1384
+ new Error('No cached credentials'),
1385
+ );
1386
+
1387
+ // Mock open to return a child process that will emit error
1388
+ const open = await import('open');
1389
+ const mockChildProcess = {
1390
+ on: vi.fn((event: string, callback: (error: Error) => void) => {
1391
+ if (event === 'error') {
1392
+ // Call the error handler immediately for testing
1393
+ setTimeout(() => callback(new Error('Process spawn failed')), 0);
1394
+ }
1395
+ }),
1396
+ };
1397
+ vi.mocked(open.default).mockResolvedValue(
1398
+ mockChildProcess as unknown as ChildProcess,
1399
+ );
1400
+
1401
+ const mockAuthResponse = {
1402
+ ok: true,
1403
+ json: async () => ({
1404
+ device_code: 'test-device-code',
1405
+ user_code: 'TEST123',
1406
+ verification_uri: 'https://chat.qwen.ai/device',
1407
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1408
+ expires_in: 1800,
1409
+ }),
1410
+ };
1411
+
1412
+ const mockTokenResponse = {
1413
+ ok: true,
1414
+ json: async () => ({
1415
+ access_token: 'new-access-token',
1416
+ refresh_token: 'new-refresh-token',
1417
+ token_type: 'Bearer',
1418
+ expires_in: 3600,
1419
+ scope: 'openid profile email model.completion',
1420
+ }),
1421
+ };
1422
+
1423
+ vi.mocked(global.fetch)
1424
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1425
+ .mockResolvedValue(mockTokenResponse as Response);
1426
+
1427
+ const client = await import('./qwenOAuth2.js').then((module) =>
1428
+ module.getQwenOAuthClient(mockConfig),
1429
+ );
1430
+
1431
+ expect(client).toBeInstanceOf(Object);
1432
+ });
1433
+ });
1434
+
1435
+ describe('Event Emitter Integration', () => {
1436
+ it('should export qwenOAuth2Events as EventEmitter', async () => {
1437
+ const { qwenOAuth2Events } = await import('./qwenOAuth2.js');
1438
+ expect(qwenOAuth2Events).toBeInstanceOf(EventEmitter);
1439
+ });
1440
+
1441
+ it('should define correct event enum values', async () => {
1442
+ const { QwenOAuth2Event } = await import('./qwenOAuth2.js');
1443
+ expect(QwenOAuth2Event.AuthUri).toBe('auth-uri');
1444
+ expect(QwenOAuth2Event.AuthProgress).toBe('auth-progress');
1445
+ expect(QwenOAuth2Event.AuthCancel).toBe('auth-cancel');
1446
+ });
1447
+ });
1448
+
1449
+ describe('Utility Functions', () => {
1450
+ describe('objectToUrlEncoded', () => {
1451
+ it('should encode object properties to URL-encoded format', async () => {
1452
+ // Since objectToUrlEncoded is private, we test it indirectly through the client
1453
+ const objectToUrlEncoded = (data: Record<string, string>): string =>
1454
+ Object.keys(data)
1455
+ .map(
1456
+ (key) =>
1457
+ `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`,
1458
+ )
1459
+ .join('&');
1460
+
1461
+ const testData = {
1462
+ client_id: 'test-client',
1463
+ scope: 'openid profile',
1464
+ redirect_uri: 'https://example.com/callback',
1465
+ };
1466
+
1467
+ const result = objectToUrlEncoded(testData);
1468
+
1469
+ expect(result).toContain('client_id=test-client');
1470
+ expect(result).toContain('scope=openid%20profile');
1471
+ expect(result).toContain(
1472
+ 'redirect_uri=https%3A%2F%2Fexample.com%2Fcallback',
1473
+ );
1474
+ });
1475
+
1476
+ it('should handle special characters', async () => {
1477
+ const objectToUrlEncoded = (data: Record<string, string>): string =>
1478
+ Object.keys(data)
1479
+ .map(
1480
+ (key) =>
1481
+ `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`,
1482
+ )
1483
+ .join('&');
1484
+
1485
+ const testData = {
1486
+ 'param with spaces': 'value with spaces',
1487
+ 'param&with&amps': 'value&with&amps',
1488
+ 'param=with=equals': 'value=with=equals',
1489
+ };
1490
+
1491
+ const result = objectToUrlEncoded(testData);
1492
+
1493
+ expect(result).toContain('param%20with%20spaces=value%20with%20spaces');
1494
+ expect(result).toContain('param%26with%26amps=value%26with%26amps');
1495
+ expect(result).toContain('param%3Dwith%3Dequals=value%3Dwith%3Dequals');
1496
+ });
1497
+
1498
+ it('should handle empty object', async () => {
1499
+ const objectToUrlEncoded = (data: Record<string, string>): string =>
1500
+ Object.keys(data)
1501
+ .map(
1502
+ (key) =>
1503
+ `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`,
1504
+ )
1505
+ .join('&');
1506
+
1507
+ const result = objectToUrlEncoded({});
1508
+ expect(result).toBe('');
1509
+ });
1510
+ });
1511
+
1512
+ describe('getQwenCachedCredentialPath', () => {
1513
+ it('should return correct path to cached credentials', async () => {
1514
+ const os = await import('os');
1515
+ const path = await import('path');
1516
+
1517
+ const expectedPath = path.join(os.homedir(), '.qwen', 'oauth_creds.json');
1518
+
1519
+ // Since this is a private function, we test it indirectly through clearQwenCredentials
1520
+ const { promises: fs } = await import('node:fs');
1521
+ const { clearQwenCredentials } = await import('./qwenOAuth2.js');
1522
+
1523
+ vi.mocked(fs.unlink).mockResolvedValue(undefined);
1524
+
1525
+ await clearQwenCredentials();
1526
+
1527
+ expect(fs.unlink).toHaveBeenCalledWith(expectedPath);
1528
+ });
1529
+ });
1530
+ });
1531
+
1532
+ describe('Credential Caching Functions', () => {
1533
+ describe('cacheQwenCredentials', () => {
1534
+ it('should create directory and write credentials to file', async () => {
1535
+ // Mock the internal cacheQwenCredentials function by creating client and calling refresh
1536
+ const client = new QwenOAuth2Client();
1537
+ client.setCredentials({
1538
+ refresh_token: 'test-refresh',
1539
+ });
1540
+
1541
+ const mockResponse = {
1542
+ ok: true,
1543
+ json: async () => ({
1544
+ access_token: 'new-token',
1545
+ token_type: 'Bearer',
1546
+ expires_in: 3600,
1547
+ }),
1548
+ };
1549
+
1550
+ global.fetch = vi.fn().mockResolvedValue(mockResponse as Response);
1551
+
1552
+ await client.refreshAccessToken();
1553
+
1554
+ // Note: File caching is now handled by SharedTokenManager, so these calls won't happen
1555
+ // This test verifies that refreshAccessToken works correctly
1556
+ const updatedCredentials = client.getCredentials();
1557
+ expect(updatedCredentials.access_token).toBe('new-token');
1558
+ });
1559
+ });
1560
+
1561
+ describe('loadCachedQwenCredentials', () => {
1562
+ it('should load and validate cached credentials successfully', async () => {
1563
+ const { promises: fs } = await import('node:fs');
1564
+ const mockCredentials = {
1565
+ access_token: 'cached-token',
1566
+ refresh_token: 'cached-refresh',
1567
+ token_type: 'Bearer',
1568
+ expiry_date: Date.now() + 3600000,
1569
+ };
1570
+
1571
+ vi.mocked(fs.readFile).mockResolvedValue(JSON.stringify(mockCredentials));
1572
+
1573
+ // Test through getQwenOAuthClient which calls loadCachedQwenCredentials
1574
+ const mockConfig = {
1575
+ isBrowserLaunchSuppressed: vi.fn().mockReturnValue(true),
1576
+ } as unknown as Config;
1577
+
1578
+ // Make SharedTokenManager fail to test the fallback
1579
+ const mockTokenManager = {
1580
+ getValidCredentials: vi
1581
+ .fn()
1582
+ .mockRejectedValue(new Error('No cached creds')),
1583
+ };
1584
+
1585
+ const originalGetInstance = SharedTokenManager.getInstance;
1586
+ SharedTokenManager.getInstance = vi
1587
+ .fn()
1588
+ .mockReturnValue(mockTokenManager);
1589
+
1590
+ // Mock successful auth flow after cache load fails
1591
+ const mockAuthResponse = {
1592
+ ok: true,
1593
+ json: async () => ({
1594
+ device_code: 'test-device-code',
1595
+ user_code: 'TEST123',
1596
+ verification_uri: 'https://chat.qwen.ai/device',
1597
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1598
+ expires_in: 1800,
1599
+ }),
1600
+ };
1601
+
1602
+ const mockTokenResponse = {
1603
+ ok: true,
1604
+ json: async () => ({
1605
+ access_token: 'new-access-token',
1606
+ refresh_token: 'new-refresh-token',
1607
+ token_type: 'Bearer',
1608
+ expires_in: 3600,
1609
+ scope: 'openid profile email model.completion',
1610
+ }),
1611
+ };
1612
+
1613
+ global.fetch = vi
1614
+ .fn()
1615
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1616
+ .mockResolvedValue(mockTokenResponse as Response);
1617
+
1618
+ try {
1619
+ await import('./qwenOAuth2.js').then((module) =>
1620
+ module.getQwenOAuthClient(mockConfig),
1621
+ );
1622
+ } catch {
1623
+ // Expected to fail in test environment
1624
+ }
1625
+
1626
+ expect(fs.readFile).toHaveBeenCalled();
1627
+ SharedTokenManager.getInstance = originalGetInstance;
1628
+ });
1629
+
1630
+ it('should handle invalid cached credentials gracefully', async () => {
1631
+ const { promises: fs } = await import('node:fs');
1632
+
1633
+ // Mock file read to return invalid JSON
1634
+ vi.mocked(fs.readFile).mockResolvedValue('invalid-json');
1635
+
1636
+ const mockConfig = {
1637
+ isBrowserLaunchSuppressed: vi.fn().mockReturnValue(true),
1638
+ } as unknown as Config;
1639
+
1640
+ const mockTokenManager = {
1641
+ getValidCredentials: vi
1642
+ .fn()
1643
+ .mockRejectedValue(new Error('No cached creds')),
1644
+ };
1645
+
1646
+ const originalGetInstance = SharedTokenManager.getInstance;
1647
+ SharedTokenManager.getInstance = vi
1648
+ .fn()
1649
+ .mockReturnValue(mockTokenManager);
1650
+
1651
+ // Mock auth flow
1652
+ const mockAuthResponse = {
1653
+ ok: true,
1654
+ json: async () => ({
1655
+ device_code: 'test-device-code',
1656
+ user_code: 'TEST123',
1657
+ verification_uri: 'https://chat.qwen.ai/device',
1658
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1659
+ expires_in: 1800,
1660
+ }),
1661
+ };
1662
+
1663
+ const mockTokenResponse = {
1664
+ ok: true,
1665
+ json: async () => ({
1666
+ access_token: 'new-token',
1667
+ refresh_token: 'new-refresh',
1668
+ token_type: 'Bearer',
1669
+ expires_in: 3600,
1670
+ }),
1671
+ };
1672
+
1673
+ global.fetch = vi
1674
+ .fn()
1675
+ .mockResolvedValueOnce(mockAuthResponse as Response)
1676
+ .mockResolvedValue(mockTokenResponse as Response);
1677
+
1678
+ try {
1679
+ await import('./qwenOAuth2.js').then((module) =>
1680
+ module.getQwenOAuthClient(mockConfig),
1681
+ );
1682
+ } catch {
1683
+ // Expected to fail in test environment
1684
+ }
1685
+
1686
+ SharedTokenManager.getInstance = originalGetInstance;
1687
+ });
1688
+
1689
+ it('should handle file access errors', async () => {
1690
+ const { promises: fs } = await import('node:fs');
1691
+
1692
+ vi.mocked(fs.readFile).mockRejectedValue(new Error('File not found'));
1693
+
1694
+ const mockConfig = {
1695
+ isBrowserLaunchSuppressed: vi.fn().mockReturnValue(true),
1696
+ } as unknown as Config;
1697
+
1698
+ const mockTokenManager = {
1699
+ getValidCredentials: vi
1700
+ .fn()
1701
+ .mockRejectedValue(new Error('No cached creds')),
1702
+ };
1703
+
1704
+ const originalGetInstance = SharedTokenManager.getInstance;
1705
+ SharedTokenManager.getInstance = vi
1706
+ .fn()
1707
+ .mockReturnValue(mockTokenManager);
1708
+
1709
+ // Mock device flow to fail quickly
1710
+ const mockAuthResponse = {
1711
+ ok: true,
1712
+ json: async () => ({
1713
+ error: 'invalid_request',
1714
+ error_description: 'Invalid request parameters',
1715
+ }),
1716
+ };
1717
+
1718
+ global.fetch = vi.fn().mockResolvedValue(mockAuthResponse as Response);
1719
+
1720
+ // Should proceed to device flow when cache loading fails
1721
+ try {
1722
+ await import('./qwenOAuth2.js').then((module) =>
1723
+ module.getQwenOAuthClient(mockConfig),
1724
+ );
1725
+ } catch {
1726
+ // Expected to fail in test environment
1727
+ }
1728
+
1729
+ SharedTokenManager.getInstance = originalGetInstance;
1730
+ });
1731
+ });
1732
+ });
1733
+
1734
+ describe('Enhanced Error Handling and Edge Cases', () => {
1735
+ let client: QwenOAuth2Client;
1736
+ let originalFetch: typeof global.fetch;
1737
+
1738
+ beforeEach(() => {
1739
+ client = new QwenOAuth2Client();
1740
+ originalFetch = global.fetch;
1741
+ global.fetch = vi.fn();
1742
+ });
1743
+
1744
+ afterEach(() => {
1745
+ global.fetch = originalFetch;
1746
+ vi.clearAllMocks();
1747
+ });
1748
+
1749
+ describe('QwenOAuth2Client getAccessToken enhanced scenarios', () => {
1750
+ it('should handle SharedTokenManager failure and fall back to cached token', async () => {
1751
+ // Set up client with valid credentials
1752
+ client.setCredentials({
1753
+ access_token: 'fallback-token',
1754
+ expiry_date: Date.now() + 3600000, // Valid for 1 hour
1755
+ });
1756
+
1757
+ // Override the client's SharedTokenManager instance directly to ensure it fails
1758
+ (
1759
+ client as unknown as {
1760
+ sharedManager: {
1761
+ getValidCredentials: () => Promise<QwenCredentials>;
1762
+ };
1763
+ }
1764
+ ).sharedManager = {
1765
+ getValidCredentials: vi
1766
+ .fn()
1767
+ .mockRejectedValue(new Error('Manager failed')),
1768
+ };
1769
+
1770
+ // Mock console.warn to avoid test noise
1771
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
1772
+
1773
+ const result = await client.getAccessToken();
1774
+
1775
+ expect(result.token).toBe('fallback-token');
1776
+ expect(consoleSpy).toHaveBeenCalledWith(
1777
+ 'Failed to get access token from shared manager:',
1778
+ expect.any(Error),
1779
+ );
1780
+
1781
+ consoleSpy.mockRestore();
1782
+ });
1783
+
1784
+ it('should return undefined when both manager and cache fail', async () => {
1785
+ // Set up client with expired credentials
1786
+ client.setCredentials({
1787
+ access_token: 'expired-token',
1788
+ expiry_date: Date.now() - 1000, // Expired
1789
+ });
1790
+
1791
+ // Override the client's SharedTokenManager instance directly to ensure it fails
1792
+ (
1793
+ client as unknown as {
1794
+ sharedManager: {
1795
+ getValidCredentials: () => Promise<QwenCredentials>;
1796
+ };
1797
+ }
1798
+ ).sharedManager = {
1799
+ getValidCredentials: vi
1800
+ .fn()
1801
+ .mockRejectedValue(new Error('Manager failed')),
1802
+ };
1803
+
1804
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
1805
+
1806
+ const result = await client.getAccessToken();
1807
+
1808
+ expect(result.token).toBeUndefined();
1809
+
1810
+ consoleSpy.mockRestore();
1811
+ });
1812
+
1813
+ it('should handle missing credentials gracefully', async () => {
1814
+ // No credentials set
1815
+ client.setCredentials({});
1816
+
1817
+ // Override the client's SharedTokenManager instance directly to ensure it fails
1818
+ (
1819
+ client as unknown as {
1820
+ sharedManager: {
1821
+ getValidCredentials: () => Promise<QwenCredentials>;
1822
+ };
1823
+ }
1824
+ ).sharedManager = {
1825
+ getValidCredentials: vi
1826
+ .fn()
1827
+ .mockRejectedValue(new Error('No credentials')),
1828
+ };
1829
+
1830
+ const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
1831
+
1832
+ const result = await client.getAccessToken();
1833
+
1834
+ expect(result.token).toBeUndefined();
1835
+
1836
+ consoleSpy.mockRestore();
1837
+ });
1838
+ });
1839
+
1840
+ describe('Enhanced requestDeviceAuthorization scenarios', () => {
1841
+ it('should include x-request-id header', async () => {
1842
+ const mockResponse = {
1843
+ ok: true,
1844
+ json: async () => ({
1845
+ device_code: 'test-device-code',
1846
+ user_code: 'TEST123',
1847
+ verification_uri: 'https://chat.qwen.ai/device',
1848
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1849
+ expires_in: 1800,
1850
+ }),
1851
+ };
1852
+
1853
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
1854
+
1855
+ await client.requestDeviceAuthorization({
1856
+ scope: 'openid profile email model.completion',
1857
+ code_challenge: 'test-challenge',
1858
+ code_challenge_method: 'S256',
1859
+ });
1860
+
1861
+ expect(global.fetch).toHaveBeenCalledWith(
1862
+ expect.any(String),
1863
+ expect.objectContaining({
1864
+ headers: expect.objectContaining({
1865
+ 'x-request-id': expect.any(String),
1866
+ }),
1867
+ }),
1868
+ );
1869
+ });
1870
+
1871
+ it('should include correct Content-Type and Accept headers', async () => {
1872
+ const mockResponse = {
1873
+ ok: true,
1874
+ json: async () => ({
1875
+ device_code: 'test-device-code',
1876
+ user_code: 'TEST123',
1877
+ verification_uri: 'https://chat.qwen.ai/device',
1878
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1879
+ expires_in: 1800,
1880
+ }),
1881
+ };
1882
+
1883
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
1884
+
1885
+ await client.requestDeviceAuthorization({
1886
+ scope: 'openid profile email model.completion',
1887
+ code_challenge: 'test-challenge',
1888
+ code_challenge_method: 'S256',
1889
+ });
1890
+
1891
+ expect(global.fetch).toHaveBeenCalledWith(
1892
+ expect.any(String),
1893
+ expect.objectContaining({
1894
+ headers: expect.objectContaining({
1895
+ 'Content-Type': 'application/x-www-form-urlencoded',
1896
+ Accept: 'application/json',
1897
+ }),
1898
+ }),
1899
+ );
1900
+ });
1901
+
1902
+ it('should send correct form data', async () => {
1903
+ const mockResponse = {
1904
+ ok: true,
1905
+ json: async () => ({
1906
+ device_code: 'test-device-code',
1907
+ user_code: 'TEST123',
1908
+ verification_uri: 'https://chat.qwen.ai/device',
1909
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
1910
+ expires_in: 1800,
1911
+ }),
1912
+ };
1913
+
1914
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
1915
+
1916
+ await client.requestDeviceAuthorization({
1917
+ scope: 'test-scope',
1918
+ code_challenge: 'test-challenge',
1919
+ code_challenge_method: 'S256',
1920
+ });
1921
+
1922
+ const [, options] = vi.mocked(global.fetch).mock.calls[0];
1923
+ expect(options?.body).toContain(
1924
+ 'client_id=f0304373b74a44d2b584a3fb70ca9e56',
1925
+ );
1926
+ expect(options?.body).toContain('scope=test-scope');
1927
+ expect(options?.body).toContain('code_challenge=test-challenge');
1928
+ expect(options?.body).toContain('code_challenge_method=S256');
1929
+ });
1930
+ });
1931
+
1932
+ describe('Enhanced pollDeviceToken scenarios', () => {
1933
+ it('should handle JSON parsing error during error response', async () => {
1934
+ const mockResponse = {
1935
+ ok: false,
1936
+ status: 400,
1937
+ statusText: 'Bad Request',
1938
+ json: vi.fn().mockRejectedValue(new Error('Invalid JSON')),
1939
+ text: vi.fn().mockResolvedValue('Invalid request format'),
1940
+ };
1941
+
1942
+ vi.mocked(global.fetch).mockResolvedValue(
1943
+ mockResponse as unknown as Response,
1944
+ );
1945
+
1946
+ await expect(
1947
+ client.pollDeviceToken({
1948
+ device_code: 'test-device-code',
1949
+ code_verifier: 'test-verifier',
1950
+ }),
1951
+ ).rejects.toThrow('Device token poll failed: 400 Bad Request');
1952
+ });
1953
+
1954
+ it('should include status code in thrown errors', async () => {
1955
+ const mockResponse = {
1956
+ ok: false,
1957
+ status: 500,
1958
+ statusText: 'Internal Server Error',
1959
+ json: vi.fn().mockRejectedValue(new Error('Invalid JSON')),
1960
+ text: vi.fn().mockResolvedValue('Internal server error'),
1961
+ };
1962
+
1963
+ global.fetch = vi
1964
+ .fn()
1965
+ .mockResolvedValue(mockResponse as unknown as Response);
1966
+
1967
+ await expect(
1968
+ client.pollDeviceToken({
1969
+ device_code: 'test-device-code',
1970
+ code_verifier: 'test-verifier',
1971
+ }),
1972
+ ).rejects.toMatchObject({
1973
+ message: expect.stringContaining(
1974
+ 'Device token poll failed: 500 Internal Server Error',
1975
+ ),
1976
+ status: 500,
1977
+ });
1978
+ });
1979
+
1980
+ it('should handle authorization_pending with correct status', async () => {
1981
+ const mockResponse = {
1982
+ ok: false,
1983
+ status: 400,
1984
+ statusText: 'Bad Request',
1985
+ json: vi.fn().mockResolvedValue({
1986
+ error: 'authorization_pending',
1987
+ error_description: 'Authorization request is pending',
1988
+ }),
1989
+ };
1990
+
1991
+ vi.mocked(global.fetch).mockResolvedValue(
1992
+ mockResponse as unknown as Response,
1993
+ );
1994
+
1995
+ const result = await client.pollDeviceToken({
1996
+ device_code: 'test-device-code',
1997
+ code_verifier: 'test-verifier',
1998
+ });
1999
+
2000
+ expect(result).toEqual({ status: 'pending' });
2001
+ });
2002
+ });
2003
+
2004
+ describe('Enhanced refreshAccessToken scenarios', () => {
2005
+ it('should call clearQwenCredentials on 400 error', async () => {
2006
+ client.setCredentials({
2007
+ refresh_token: 'expired-refresh',
2008
+ });
2009
+
2010
+ const { promises: fs } = await import('node:fs');
2011
+ vi.mocked(fs.unlink).mockResolvedValue(undefined);
2012
+
2013
+ const mockResponse = {
2014
+ ok: false,
2015
+ status: 400,
2016
+ text: async () => 'Bad Request',
2017
+ };
2018
+
2019
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
2020
+
2021
+ await expect(client.refreshAccessToken()).rejects.toThrow(
2022
+ "Refresh token expired or invalid. Please use '/auth' to re-authenticate.",
2023
+ );
2024
+
2025
+ expect(fs.unlink).toHaveBeenCalled();
2026
+ });
2027
+
2028
+ it('should preserve existing refresh token when new one not provided', async () => {
2029
+ const originalRefreshToken = 'original-refresh-token';
2030
+ client.setCredentials({
2031
+ refresh_token: originalRefreshToken,
2032
+ });
2033
+
2034
+ const mockResponse = {
2035
+ ok: true,
2036
+ json: async () => ({
2037
+ access_token: 'new-access-token',
2038
+ token_type: 'Bearer',
2039
+ expires_in: 3600,
2040
+ // No refresh_token in response
2041
+ }),
2042
+ };
2043
+
2044
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
2045
+
2046
+ await client.refreshAccessToken();
2047
+
2048
+ const credentials = client.getCredentials();
2049
+ expect(credentials.refresh_token).toBe(originalRefreshToken);
2050
+ });
2051
+
2052
+ it('should include resource_url when provided in response', async () => {
2053
+ client.setCredentials({
2054
+ refresh_token: 'test-refresh',
2055
+ });
2056
+
2057
+ const mockResponse = {
2058
+ ok: true,
2059
+ json: async () => ({
2060
+ access_token: 'new-access-token',
2061
+ token_type: 'Bearer',
2062
+ expires_in: 3600,
2063
+ resource_url: 'https://new-resource-url.com',
2064
+ }),
2065
+ };
2066
+
2067
+ vi.mocked(global.fetch).mockResolvedValue(mockResponse as Response);
2068
+
2069
+ await client.refreshAccessToken();
2070
+
2071
+ const credentials = client.getCredentials();
2072
+ expect(credentials.resource_url).toBe('https://new-resource-url.com');
2073
+ });
2074
+ });
2075
+
2076
+ describe('isTokenValid edge cases', () => {
2077
+ it('should return false for tokens expiring within buffer time', () => {
2078
+ const nearExpiryTime = Date.now() + 15000; // 15 seconds from now (within 30s buffer)
2079
+
2080
+ client.setCredentials({
2081
+ access_token: 'test-token',
2082
+ expiry_date: nearExpiryTime,
2083
+ });
2084
+
2085
+ const isValid = (
2086
+ client as unknown as { isTokenValid(): boolean }
2087
+ ).isTokenValid();
2088
+ expect(isValid).toBe(false);
2089
+ });
2090
+
2091
+ it('should return true for tokens expiring well beyond buffer time', () => {
2092
+ const futureExpiryTime = Date.now() + 120000; // 2 minutes from now (beyond 30s buffer)
2093
+
2094
+ client.setCredentials({
2095
+ access_token: 'test-token',
2096
+ expiry_date: futureExpiryTime,
2097
+ });
2098
+
2099
+ const isValid = (
2100
+ client as unknown as { isTokenValid(): boolean }
2101
+ ).isTokenValid();
2102
+ expect(isValid).toBe(true);
2103
+ });
2104
+ });
2105
+ });
2106
+
2107
+ describe('SharedTokenManager Integration in QwenOAuth2Client', () => {
2108
+ let client: QwenOAuth2Client;
2109
+
2110
+ beforeEach(() => {
2111
+ client = new QwenOAuth2Client();
2112
+ });
2113
+
2114
+ it('should use SharedTokenManager instance in constructor', () => {
2115
+ const sharedManager = (
2116
+ client as unknown as { sharedManager: MockSharedTokenManager }
2117
+ ).sharedManager;
2118
+ expect(sharedManager).toBeDefined();
2119
+ });
2120
+
2121
+ it('should handle TokenManagerError types correctly in getQwenOAuthClient', async () => {
2122
+ const mockConfig = {
2123
+ isBrowserLaunchSuppressed: vi.fn().mockReturnValue(true),
2124
+ } as unknown as Config;
2125
+
2126
+ // Test different TokenManagerError types
2127
+ const tokenErrors = [
2128
+ { type: TokenError.NO_REFRESH_TOKEN, message: 'No refresh token' },
2129
+ { type: TokenError.REFRESH_FAILED, message: 'Token refresh failed' },
2130
+ { type: TokenError.NETWORK_ERROR, message: 'Network error' },
2131
+ { type: TokenError.REFRESH_FAILED, message: 'Refresh failed' },
2132
+ ];
2133
+
2134
+ for (const errorInfo of tokenErrors) {
2135
+ const tokenError = new TokenManagerError(
2136
+ errorInfo.type,
2137
+ errorInfo.message,
2138
+ );
2139
+
2140
+ const mockTokenManager = {
2141
+ getValidCredentials: vi.fn().mockRejectedValue(tokenError),
2142
+ };
2143
+
2144
+ const originalGetInstance = SharedTokenManager.getInstance;
2145
+ SharedTokenManager.getInstance = vi
2146
+ .fn()
2147
+ .mockReturnValue(mockTokenManager);
2148
+
2149
+ const { promises: fs } = await import('node:fs');
2150
+ vi.mocked(fs.readFile).mockRejectedValue(new Error('No cached file'));
2151
+
2152
+ // Mock device flow to succeed
2153
+ const mockAuthResponse = {
2154
+ ok: true,
2155
+ json: async () => ({
2156
+ device_code: 'test-device-code',
2157
+ user_code: 'TEST123',
2158
+ verification_uri: 'https://chat.qwen.ai/device',
2159
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
2160
+ expires_in: 1800,
2161
+ }),
2162
+ };
2163
+
2164
+ const mockTokenResponse = {
2165
+ ok: true,
2166
+ json: async () => ({
2167
+ access_token: 'new-token',
2168
+ refresh_token: 'new-refresh',
2169
+ token_type: 'Bearer',
2170
+ expires_in: 3600,
2171
+ }),
2172
+ };
2173
+
2174
+ global.fetch = vi
2175
+ .fn()
2176
+ .mockResolvedValueOnce(mockAuthResponse as Response)
2177
+ .mockResolvedValue(mockTokenResponse as Response);
2178
+
2179
+ try {
2180
+ await import('./qwenOAuth2.js').then((module) =>
2181
+ module.getQwenOAuthClient(mockConfig),
2182
+ );
2183
+ } catch {
2184
+ // Expected to fail in test environment
2185
+ }
2186
+
2187
+ SharedTokenManager.getInstance = originalGetInstance;
2188
+ vi.clearAllMocks();
2189
+ }
2190
+ });
2191
+ });
2192
+
2193
+ describe('Constants and Configuration', () => {
2194
+ it('should have correct OAuth endpoints', async () => {
2195
+ // Test that the constants are properly defined by checking they're used in requests
2196
+ const client = new QwenOAuth2Client();
2197
+
2198
+ const mockResponse = {
2199
+ ok: true,
2200
+ json: async () => ({
2201
+ device_code: 'test-device-code',
2202
+ user_code: 'TEST123',
2203
+ verification_uri: 'https://chat.qwen.ai/device',
2204
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
2205
+ expires_in: 1800,
2206
+ }),
2207
+ };
2208
+
2209
+ global.fetch = vi.fn().mockResolvedValue(mockResponse as Response);
2210
+
2211
+ await client.requestDeviceAuthorization({
2212
+ scope: 'test-scope',
2213
+ code_challenge: 'test-challenge',
2214
+ code_challenge_method: 'S256',
2215
+ });
2216
+
2217
+ const [url] = vi.mocked(global.fetch).mock.calls[0];
2218
+ expect(url).toBe('https://chat.qwen.ai/api/v1/oauth2/device/code');
2219
+ });
2220
+
2221
+ it('should use correct client ID in requests', async () => {
2222
+ const client = new QwenOAuth2Client();
2223
+
2224
+ const mockResponse = {
2225
+ ok: true,
2226
+ json: async () => ({
2227
+ device_code: 'test-device-code',
2228
+ user_code: 'TEST123',
2229
+ verification_uri: 'https://chat.qwen.ai/device',
2230
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
2231
+ expires_in: 1800,
2232
+ }),
2233
+ };
2234
+
2235
+ global.fetch = vi.fn().mockResolvedValue(mockResponse as Response);
2236
+
2237
+ await client.requestDeviceAuthorization({
2238
+ scope: 'test-scope',
2239
+ code_challenge: 'test-challenge',
2240
+ code_challenge_method: 'S256',
2241
+ });
2242
+
2243
+ const [, options] = vi.mocked(global.fetch).mock.calls[0];
2244
+ expect(options?.body).toContain(
2245
+ 'client_id=f0304373b74a44d2b584a3fb70ca9e56',
2246
+ );
2247
+ });
2248
+
2249
+ it('should use correct default scope', async () => {
2250
+ // Test the default scope constant by checking it's used in device flow
2251
+ const client = new QwenOAuth2Client();
2252
+
2253
+ const mockResponse = {
2254
+ ok: true,
2255
+ json: async () => ({
2256
+ device_code: 'test-device-code',
2257
+ user_code: 'TEST123',
2258
+ verification_uri: 'https://chat.qwen.ai/device',
2259
+ verification_uri_complete: 'https://chat.qwen.ai/device?code=TEST123',
2260
+ expires_in: 1800,
2261
+ }),
2262
+ };
2263
+
2264
+ global.fetch = vi.fn().mockResolvedValue(mockResponse as Response);
2265
+
2266
+ await client.requestDeviceAuthorization({
2267
+ scope: 'openid profile email model.completion',
2268
+ code_challenge: 'test-challenge',
2269
+ code_challenge_method: 'S256',
2270
+ });
2271
+
2272
+ const [, options] = vi.mocked(global.fetch).mock.calls[0];
2273
+ expect(options?.body).toContain(
2274
+ 'scope=openid%20profile%20email%20model.completion',
2275
+ );
2276
+ });
2277
+ });
projects/ui/qwen-code/packages/core/src/qwen/qwenOAuth2.ts ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import crypto from 'crypto';
8
+ import path from 'node:path';
9
+ import { promises as fs } from 'node:fs';
10
+ import * as os from 'os';
11
+
12
+ import open from 'open';
13
+ import { EventEmitter } from 'events';
14
+ import { Config } from '../config/config.js';
15
+ import { randomUUID } from 'node:crypto';
16
+ import {
17
+ SharedTokenManager,
18
+ TokenManagerError,
19
+ TokenError,
20
+ } from './sharedTokenManager.js';
21
+
22
+ // OAuth Endpoints
23
+ const QWEN_OAUTH_BASE_URL = 'https://chat.qwen.ai';
24
+
25
+ const QWEN_OAUTH_DEVICE_CODE_ENDPOINT = `${QWEN_OAUTH_BASE_URL}/api/v1/oauth2/device/code`;
26
+ const QWEN_OAUTH_TOKEN_ENDPOINT = `${QWEN_OAUTH_BASE_URL}/api/v1/oauth2/token`;
27
+
28
+ // OAuth Client Configuration
29
+ const QWEN_OAUTH_CLIENT_ID = 'f0304373b74a44d2b584a3fb70ca9e56';
30
+
31
+ const QWEN_OAUTH_SCOPE = 'openid profile email model.completion';
32
+ const QWEN_OAUTH_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:device_code';
33
+
34
+ // File System Configuration
35
+ const QWEN_DIR = '.qwen';
36
+ const QWEN_CREDENTIAL_FILENAME = 'oauth_creds.json';
37
+
38
+ // Token Configuration
39
+ const TOKEN_REFRESH_BUFFER_MS = 30 * 1000; // 30 seconds
40
+
41
+ /**
42
+ * PKCE (Proof Key for Code Exchange) utilities
43
+ * Implements RFC 7636 - Proof Key for Code Exchange by OAuth Public Clients
44
+ */
45
+
46
+ /**
47
+ * Generate a random code verifier for PKCE
48
+ * @returns A random string of 43-128 characters
49
+ */
50
+ export function generateCodeVerifier(): string {
51
+ return crypto.randomBytes(32).toString('base64url');
52
+ }
53
+
54
+ /**
55
+ * Generate a code challenge from a code verifier using SHA-256
56
+ * @param codeVerifier The code verifier string
57
+ * @returns The code challenge string
58
+ */
59
+ export function generateCodeChallenge(codeVerifier: string): string {
60
+ const hash = crypto.createHash('sha256');
61
+ hash.update(codeVerifier);
62
+ return hash.digest('base64url');
63
+ }
64
+
65
+ /**
66
+ * Generate PKCE code verifier and challenge pair
67
+ * @returns Object containing code_verifier and code_challenge
68
+ */
69
+ export function generatePKCEPair(): {
70
+ code_verifier: string;
71
+ code_challenge: string;
72
+ } {
73
+ const codeVerifier = generateCodeVerifier();
74
+ const codeChallenge = generateCodeChallenge(codeVerifier);
75
+ return { code_verifier: codeVerifier, code_challenge: codeChallenge };
76
+ }
77
+
78
+ /**
79
+ * Convert object to URL-encoded form data
80
+ * @param data The object to convert
81
+ * @returns URL-encoded string
82
+ */
83
+ function objectToUrlEncoded(data: Record<string, string>): string {
84
+ return Object.keys(data)
85
+ .map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
86
+ .join('&');
87
+ }
88
+
89
+ /**
90
+ * Standard error response data
91
+ */
92
+ export interface ErrorData {
93
+ error: string;
94
+ error_description: string;
95
+ }
96
+
97
+ /**
98
+ * Qwen OAuth2 credentials interface
99
+ */
100
+ export interface QwenCredentials {
101
+ access_token?: string;
102
+ refresh_token?: string;
103
+ id_token?: string;
104
+ expiry_date?: number;
105
+ token_type?: string;
106
+ resource_url?: string;
107
+ }
108
+
109
+ /**
110
+ * Device authorization success data
111
+ */
112
+ export interface DeviceAuthorizationData {
113
+ device_code: string;
114
+ user_code: string;
115
+ verification_uri: string;
116
+ verification_uri_complete: string;
117
+ expires_in: number;
118
+ }
119
+
120
+ /**
121
+ * Device authorization response interface
122
+ */
123
+ export type DeviceAuthorizationResponse = DeviceAuthorizationData | ErrorData;
124
+
125
+ /**
126
+ * Type guard to check if device authorization was successful
127
+ */
128
+ export function isDeviceAuthorizationSuccess(
129
+ response: DeviceAuthorizationResponse,
130
+ ): response is DeviceAuthorizationData {
131
+ return 'device_code' in response;
132
+ }
133
+
134
+ /**
135
+ * Device token success data
136
+ */
137
+ export interface DeviceTokenData {
138
+ access_token: string | null;
139
+ refresh_token?: string | null;
140
+ token_type: string;
141
+ expires_in: number | null;
142
+ scope?: string | null;
143
+ endpoint?: string;
144
+ resource_url?: string;
145
+ }
146
+
147
+ /**
148
+ * Device token pending response
149
+ */
150
+ export interface DeviceTokenPendingData {
151
+ status: 'pending';
152
+ slowDown?: boolean; // Indicates if client should increase polling interval
153
+ }
154
+
155
+ /**
156
+ * Device token response interface
157
+ */
158
+ export type DeviceTokenResponse =
159
+ | DeviceTokenData
160
+ | DeviceTokenPendingData
161
+ | ErrorData;
162
+
163
+ /**
164
+ * Type guard to check if device token response was successful
165
+ */
166
+ export function isDeviceTokenSuccess(
167
+ response: DeviceTokenResponse,
168
+ ): response is DeviceTokenData {
169
+ return (
170
+ 'access_token' in response &&
171
+ response.access_token !== null &&
172
+ response.access_token !== undefined &&
173
+ typeof response.access_token === 'string' &&
174
+ response.access_token.length > 0
175
+ );
176
+ }
177
+
178
+ /**
179
+ * Type guard to check if device token response is pending
180
+ */
181
+ export function isDeviceTokenPending(
182
+ response: DeviceTokenResponse,
183
+ ): response is DeviceTokenPendingData {
184
+ return (
185
+ 'status' in response &&
186
+ (response as DeviceTokenPendingData).status === 'pending'
187
+ );
188
+ }
189
+
190
+ /**
191
+ * Type guard to check if response is an error
192
+ */
193
+ export function isErrorResponse(
194
+ response:
195
+ | DeviceAuthorizationResponse
196
+ | DeviceTokenResponse
197
+ | TokenRefreshResponse,
198
+ ): response is ErrorData {
199
+ return 'error' in response;
200
+ }
201
+
202
+ /**
203
+ * Token refresh success data
204
+ */
205
+ export interface TokenRefreshData {
206
+ access_token: string;
207
+ token_type: string;
208
+ expires_in: number;
209
+ refresh_token?: string; // Some OAuth servers may return a new refresh token
210
+ resource_url?: string;
211
+ }
212
+
213
+ /**
214
+ * Token refresh response interface
215
+ */
216
+ export type TokenRefreshResponse = TokenRefreshData | ErrorData;
217
+
218
+ /**
219
+ * Qwen OAuth2 client interface
220
+ */
221
+ export interface IQwenOAuth2Client {
222
+ setCredentials(credentials: QwenCredentials): void;
223
+ getCredentials(): QwenCredentials;
224
+ getAccessToken(): Promise<{ token?: string }>;
225
+ requestDeviceAuthorization(options: {
226
+ scope: string;
227
+ code_challenge: string;
228
+ code_challenge_method: string;
229
+ }): Promise<DeviceAuthorizationResponse>;
230
+ pollDeviceToken(options: {
231
+ device_code: string;
232
+ code_verifier: string;
233
+ }): Promise<DeviceTokenResponse>;
234
+ refreshAccessToken(): Promise<TokenRefreshResponse>;
235
+ }
236
+
237
+ /**
238
+ * Qwen OAuth2 client implementation
239
+ */
240
+ export class QwenOAuth2Client implements IQwenOAuth2Client {
241
+ private credentials: QwenCredentials = {};
242
+ private sharedManager: SharedTokenManager;
243
+
244
+ constructor() {
245
+ this.sharedManager = SharedTokenManager.getInstance();
246
+ }
247
+
248
+ setCredentials(credentials: QwenCredentials): void {
249
+ this.credentials = credentials;
250
+ }
251
+
252
+ getCredentials(): QwenCredentials {
253
+ return this.credentials;
254
+ }
255
+
256
+ async getAccessToken(): Promise<{ token?: string }> {
257
+ try {
258
+ // Use shared manager to get valid credentials with cross-session synchronization
259
+ const credentials = await this.sharedManager.getValidCredentials(this);
260
+ return { token: credentials.access_token };
261
+ } catch (error) {
262
+ console.warn('Failed to get access token from shared manager:', error);
263
+
264
+ // Only return cached token if it's still valid, don't refresh uncoordinated
265
+ // This prevents the cross-session token invalidation issue
266
+ if (this.credentials.access_token && this.isTokenValid()) {
267
+ return { token: this.credentials.access_token };
268
+ }
269
+
270
+ // If we can't get valid credentials through shared manager, fail gracefully
271
+ // All token refresh operations should go through the SharedTokenManager
272
+ return { token: undefined };
273
+ }
274
+ }
275
+
276
+ async requestDeviceAuthorization(options: {
277
+ scope: string;
278
+ code_challenge: string;
279
+ code_challenge_method: string;
280
+ }): Promise<DeviceAuthorizationResponse> {
281
+ const bodyData = {
282
+ client_id: QWEN_OAUTH_CLIENT_ID,
283
+ scope: options.scope,
284
+ code_challenge: options.code_challenge,
285
+ code_challenge_method: options.code_challenge_method,
286
+ };
287
+
288
+ const response = await fetch(QWEN_OAUTH_DEVICE_CODE_ENDPOINT, {
289
+ method: 'POST',
290
+ headers: {
291
+ 'Content-Type': 'application/x-www-form-urlencoded',
292
+ Accept: 'application/json',
293
+ 'x-request-id': randomUUID(),
294
+ },
295
+ body: objectToUrlEncoded(bodyData),
296
+ });
297
+
298
+ if (!response.ok) {
299
+ const errorData = await response.text();
300
+ throw new Error(
301
+ `Device authorization failed: ${response.status} ${response.statusText}. Response: ${errorData}`,
302
+ );
303
+ }
304
+
305
+ const result = (await response.json()) as DeviceAuthorizationResponse;
306
+ console.debug('Device authorization result:', result);
307
+
308
+ // Check if the response indicates success
309
+ if (!isDeviceAuthorizationSuccess(result)) {
310
+ const errorData = result as ErrorData;
311
+ throw new Error(
312
+ `Device authorization failed: ${errorData?.error || 'Unknown error'} - ${errorData?.error_description || 'No details provided'}`,
313
+ );
314
+ }
315
+
316
+ return result;
317
+ }
318
+
319
+ async pollDeviceToken(options: {
320
+ device_code: string;
321
+ code_verifier: string;
322
+ }): Promise<DeviceTokenResponse> {
323
+ const bodyData = {
324
+ grant_type: QWEN_OAUTH_GRANT_TYPE,
325
+ client_id: QWEN_OAUTH_CLIENT_ID,
326
+ device_code: options.device_code,
327
+ code_verifier: options.code_verifier,
328
+ };
329
+
330
+ const response = await fetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
331
+ method: 'POST',
332
+ headers: {
333
+ 'Content-Type': 'application/x-www-form-urlencoded',
334
+ Accept: 'application/json',
335
+ },
336
+ body: objectToUrlEncoded(bodyData),
337
+ });
338
+
339
+ if (!response.ok) {
340
+ // Parse the response as JSON to check for OAuth RFC 8628 standard errors
341
+ try {
342
+ const errorData = (await response.json()) as ErrorData;
343
+
344
+ // According to OAuth RFC 8628, handle standard polling responses
345
+ if (
346
+ response.status === 400 &&
347
+ errorData.error === 'authorization_pending'
348
+ ) {
349
+ // User has not yet approved the authorization request. Continue polling.
350
+ return { status: 'pending' } as DeviceTokenPendingData;
351
+ }
352
+
353
+ if (response.status === 429 && errorData.error === 'slow_down') {
354
+ // Client is polling too frequently. Return pending with slowDown flag.
355
+ return {
356
+ status: 'pending',
357
+ slowDown: true,
358
+ } as DeviceTokenPendingData;
359
+ }
360
+
361
+ // Handle other 400 errors (access_denied, expired_token, etc.) as real errors
362
+
363
+ // For other errors, throw with proper error information
364
+ const error = new Error(
365
+ `Device token poll failed: ${errorData.error || 'Unknown error'} - ${errorData.error_description || 'No details provided'}`,
366
+ );
367
+ (error as Error & { status?: number }).status = response.status;
368
+ throw error;
369
+ } catch (_parseError) {
370
+ // If JSON parsing fails, fall back to text response
371
+ const errorData = await response.text();
372
+ const error = new Error(
373
+ `Device token poll failed: ${response.status} ${response.statusText}. Response: ${errorData}`,
374
+ );
375
+ (error as Error & { status?: number }).status = response.status;
376
+ throw error;
377
+ }
378
+ }
379
+
380
+ return (await response.json()) as DeviceTokenResponse;
381
+ }
382
+
383
+ async refreshAccessToken(): Promise<TokenRefreshResponse> {
384
+ if (!this.credentials.refresh_token) {
385
+ throw new Error('No refresh token available');
386
+ }
387
+
388
+ const bodyData = {
389
+ grant_type: 'refresh_token',
390
+ refresh_token: this.credentials.refresh_token,
391
+ client_id: QWEN_OAUTH_CLIENT_ID,
392
+ };
393
+
394
+ const response = await fetch(QWEN_OAUTH_TOKEN_ENDPOINT, {
395
+ method: 'POST',
396
+ headers: {
397
+ 'Content-Type': 'application/x-www-form-urlencoded',
398
+ Accept: 'application/json',
399
+ },
400
+ body: objectToUrlEncoded(bodyData),
401
+ });
402
+
403
+ if (!response.ok) {
404
+ const errorData = await response.text();
405
+ // Handle 401 errors which might indicate refresh token expiry
406
+ if (response.status === 400) {
407
+ await clearQwenCredentials();
408
+ throw new Error(
409
+ "Refresh token expired or invalid. Please use '/auth' to re-authenticate.",
410
+ );
411
+ }
412
+ throw new Error(
413
+ `Token refresh failed: ${response.status} ${response.statusText}. Response: ${errorData}`,
414
+ );
415
+ }
416
+
417
+ const responseData = (await response.json()) as TokenRefreshResponse;
418
+
419
+ // Check if the response indicates success
420
+ if (isErrorResponse(responseData)) {
421
+ const errorData = responseData as ErrorData;
422
+ throw new Error(
423
+ `Token refresh failed: ${errorData?.error || 'Unknown error'} - ${errorData?.error_description || 'No details provided'}`,
424
+ );
425
+ }
426
+
427
+ // Handle successful response
428
+ const tokenData = responseData as TokenRefreshData;
429
+ const tokens: QwenCredentials = {
430
+ access_token: tokenData.access_token,
431
+ token_type: tokenData.token_type,
432
+ // Use new refresh token if provided, otherwise preserve existing one
433
+ refresh_token: tokenData.refresh_token || this.credentials.refresh_token,
434
+ resource_url: tokenData.resource_url, // Include resource_url if provided
435
+ expiry_date: Date.now() + tokenData.expires_in * 1000,
436
+ };
437
+
438
+ this.setCredentials(tokens);
439
+
440
+ // Note: File caching is now handled by SharedTokenManager
441
+ // to prevent cross-session token invalidation issues
442
+
443
+ return responseData;
444
+ }
445
+
446
+ private isTokenValid(): boolean {
447
+ if (!this.credentials.expiry_date) {
448
+ return false;
449
+ }
450
+ // Check if token expires within the refresh buffer time
451
+ return Date.now() < this.credentials.expiry_date - TOKEN_REFRESH_BUFFER_MS;
452
+ }
453
+ }
454
+
455
+ export enum QwenOAuth2Event {
456
+ AuthUri = 'auth-uri',
457
+ AuthProgress = 'auth-progress',
458
+ AuthCancel = 'auth-cancel',
459
+ }
460
+
461
+ /**
462
+ * Authentication result types to distinguish different failure reasons
463
+ */
464
+ export type AuthResult =
465
+ | { success: true }
466
+ | {
467
+ success: false;
468
+ reason: 'timeout' | 'cancelled' | 'error' | 'rate_limit';
469
+ };
470
+
471
+ /**
472
+ * Global event emitter instance for QwenOAuth2 authentication events
473
+ */
474
+ export const qwenOAuth2Events = new EventEmitter();
475
+
476
+ export async function getQwenOAuthClient(
477
+ config: Config,
478
+ ): Promise<QwenOAuth2Client> {
479
+ const client = new QwenOAuth2Client();
480
+
481
+ // Use shared token manager to get valid credentials with cross-session synchronization
482
+ const sharedManager = SharedTokenManager.getInstance();
483
+
484
+ try {
485
+ // Try to get valid credentials from shared cache first
486
+ const credentials = await sharedManager.getValidCredentials(client);
487
+ client.setCredentials(credentials);
488
+ return client;
489
+ } catch (error: unknown) {
490
+ console.debug(
491
+ 'Shared token manager failed, attempting device flow:',
492
+ error,
493
+ );
494
+
495
+ // Handle specific token manager errors
496
+ if (error instanceof TokenManagerError) {
497
+ switch (error.type) {
498
+ case TokenError.NO_REFRESH_TOKEN:
499
+ console.debug(
500
+ 'No refresh token available, proceeding with device flow',
501
+ );
502
+ break;
503
+ case TokenError.REFRESH_FAILED:
504
+ console.debug('Token refresh failed, proceeding with device flow');
505
+ break;
506
+ case TokenError.NETWORK_ERROR:
507
+ console.warn(
508
+ 'Network error during token refresh, trying device flow',
509
+ );
510
+ break;
511
+ default:
512
+ console.warn('Token manager error:', (error as Error).message);
513
+ }
514
+ }
515
+
516
+ // If shared manager fails, check if we have cached credentials for device flow
517
+ if (await loadCachedQwenCredentials(client)) {
518
+ // We have cached credentials but they might be expired
519
+ // Try device flow instead of forcing refresh
520
+ const result = await authWithQwenDeviceFlow(client, config);
521
+ if (!result.success) {
522
+ throw new Error('Qwen OAuth authentication failed');
523
+ }
524
+ return client;
525
+ }
526
+
527
+ // No cached credentials, use device authorization flow for authentication
528
+ const result = await authWithQwenDeviceFlow(client, config);
529
+ if (!result.success) {
530
+ // Only emit timeout event if the failure reason is actually timeout
531
+ // Other error types (401, 429, etc.) have already emitted their specific events
532
+ if (result.reason === 'timeout') {
533
+ qwenOAuth2Events.emit(
534
+ QwenOAuth2Event.AuthProgress,
535
+ 'timeout',
536
+ 'Authentication timed out. Please try again or select a different authentication method.',
537
+ );
538
+ }
539
+
540
+ // Throw error with appropriate message based on failure reason
541
+ switch (result.reason) {
542
+ case 'timeout':
543
+ throw new Error('Qwen OAuth authentication timed out');
544
+ case 'cancelled':
545
+ throw new Error('Qwen OAuth authentication was cancelled by user');
546
+ case 'rate_limit':
547
+ throw new Error(
548
+ 'Too many request for Qwen OAuth authentication, please try again later.',
549
+ );
550
+ case 'error':
551
+ default:
552
+ throw new Error('Qwen OAuth authentication failed');
553
+ }
554
+ }
555
+
556
+ return client;
557
+ }
558
+ }
559
+
560
+ async function authWithQwenDeviceFlow(
561
+ client: QwenOAuth2Client,
562
+ config: Config,
563
+ ): Promise<AuthResult> {
564
+ let isCancelled = false;
565
+
566
+ // Set up cancellation listener
567
+ const cancelHandler = () => {
568
+ isCancelled = true;
569
+ };
570
+ qwenOAuth2Events.once(QwenOAuth2Event.AuthCancel, cancelHandler);
571
+
572
+ try {
573
+ // Generate PKCE code verifier and challenge
574
+ const { code_verifier, code_challenge } = generatePKCEPair();
575
+
576
+ // Request device authorization
577
+ const deviceAuth = await client.requestDeviceAuthorization({
578
+ scope: QWEN_OAUTH_SCOPE,
579
+ code_challenge,
580
+ code_challenge_method: 'S256',
581
+ });
582
+
583
+ // Ensure we have a successful authorization response
584
+ if (!isDeviceAuthorizationSuccess(deviceAuth)) {
585
+ const errorData = deviceAuth as ErrorData;
586
+ throw new Error(
587
+ `Device authorization failed: ${errorData?.error || 'Unknown error'} - ${errorData?.error_description || 'No details provided'}`,
588
+ );
589
+ }
590
+
591
+ // Emit device authorization event for UI integration immediately
592
+ qwenOAuth2Events.emit(QwenOAuth2Event.AuthUri, deviceAuth);
593
+
594
+ const showFallbackMessage = () => {
595
+ console.log('\n=== Qwen OAuth Device Authorization ===');
596
+ console.log(
597
+ 'Please visit the following URL in your browser to authorize:',
598
+ );
599
+ console.log(`\n${deviceAuth.verification_uri_complete}\n`);
600
+ console.log('Waiting for authorization to complete...\n');
601
+ };
602
+
603
+ // If browser launch is not suppressed, try to open the URL
604
+ if (!config.isBrowserLaunchSuppressed()) {
605
+ try {
606
+ const childProcess = await open(deviceAuth.verification_uri_complete);
607
+
608
+ // IMPORTANT: Attach an error handler to the returned child process.
609
+ // Without this, if `open` fails to spawn a process (e.g., `xdg-open` is not found
610
+ // in a minimal Docker container), it will emit an unhandled 'error' event,
611
+ // causing the entire Node.js process to crash.
612
+ if (childProcess) {
613
+ childProcess.on('error', () => {
614
+ console.debug(
615
+ 'Failed to open browser. Visit this URL to authorize:',
616
+ );
617
+ showFallbackMessage();
618
+ });
619
+ }
620
+ } catch (_err) {
621
+ showFallbackMessage();
622
+ }
623
+ } else {
624
+ // Browser launch is suppressed, show fallback message
625
+ showFallbackMessage();
626
+ }
627
+
628
+ // Emit auth progress event
629
+ qwenOAuth2Events.emit(
630
+ QwenOAuth2Event.AuthProgress,
631
+ 'polling',
632
+ 'Waiting for authorization...',
633
+ );
634
+
635
+ console.debug('Waiting for authorization...\n');
636
+
637
+ // Poll for the token
638
+ let pollInterval = 2000; // 2 seconds, can be increased if slow_down is received
639
+ const maxAttempts = Math.ceil(
640
+ deviceAuth.expires_in / (pollInterval / 1000),
641
+ );
642
+
643
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
644
+ // Check if authentication was cancelled
645
+ if (isCancelled) {
646
+ console.debug('\nAuthentication cancelled by user.');
647
+ qwenOAuth2Events.emit(
648
+ QwenOAuth2Event.AuthProgress,
649
+ 'error',
650
+ 'Authentication cancelled by user.',
651
+ );
652
+ return { success: false, reason: 'cancelled' };
653
+ }
654
+
655
+ try {
656
+ console.debug('polling for token...');
657
+ const tokenResponse = await client.pollDeviceToken({
658
+ device_code: deviceAuth.device_code,
659
+ code_verifier,
660
+ });
661
+
662
+ // Check if the response is successful and contains token data
663
+ if (isDeviceTokenSuccess(tokenResponse)) {
664
+ const tokenData = tokenResponse as DeviceTokenData;
665
+
666
+ // Convert to QwenCredentials format
667
+ const credentials: QwenCredentials = {
668
+ access_token: tokenData.access_token!, // Safe to assert as non-null due to isDeviceTokenSuccess check
669
+ refresh_token: tokenData.refresh_token || undefined,
670
+ token_type: tokenData.token_type,
671
+ resource_url: tokenData.resource_url,
672
+ expiry_date: tokenData.expires_in
673
+ ? Date.now() + tokenData.expires_in * 1000
674
+ : undefined,
675
+ };
676
+
677
+ client.setCredentials(credentials);
678
+
679
+ // Cache the new tokens
680
+ await cacheQwenCredentials(credentials);
681
+
682
+ // Emit auth progress success event
683
+ qwenOAuth2Events.emit(
684
+ QwenOAuth2Event.AuthProgress,
685
+ 'success',
686
+ 'Authentication successful! Access token obtained.',
687
+ );
688
+
689
+ console.debug('Authentication successful! Access token obtained.');
690
+ return { success: true };
691
+ }
692
+
693
+ // Check if the response is pending
694
+ if (isDeviceTokenPending(tokenResponse)) {
695
+ const pendingData = tokenResponse as DeviceTokenPendingData;
696
+
697
+ // Handle slow_down error by increasing poll interval
698
+ if (pendingData.slowDown) {
699
+ pollInterval = Math.min(pollInterval * 1.5, 10000); // Increase by 50%, max 10 seconds
700
+ console.debug(
701
+ `\nServer requested to slow down, increasing poll interval to ${pollInterval}ms'`,
702
+ );
703
+ } else {
704
+ pollInterval = 2000; // Reset to default interval
705
+ }
706
+
707
+ // Emit polling progress event
708
+ qwenOAuth2Events.emit(
709
+ QwenOAuth2Event.AuthProgress,
710
+ 'polling',
711
+ `Polling... (attempt ${attempt + 1}/${maxAttempts})`,
712
+ );
713
+
714
+ process.stdout.write('.');
715
+
716
+ // Wait with cancellation check every 100ms
717
+ await new Promise<void>((resolve) => {
718
+ const checkInterval = 100; // Check every 100ms
719
+ let elapsedTime = 0;
720
+
721
+ const intervalId = setInterval(() => {
722
+ elapsedTime += checkInterval;
723
+
724
+ // Check for cancellation during wait
725
+ if (isCancelled) {
726
+ clearInterval(intervalId);
727
+ resolve();
728
+ return;
729
+ }
730
+
731
+ // Complete wait when interval is reached
732
+ if (elapsedTime >= pollInterval) {
733
+ clearInterval(intervalId);
734
+ resolve();
735
+ return;
736
+ }
737
+ }, checkInterval);
738
+ });
739
+
740
+ // Check for cancellation after waiting
741
+ if (isCancelled) {
742
+ console.debug('\nAuthentication cancelled by user.');
743
+ qwenOAuth2Events.emit(
744
+ QwenOAuth2Event.AuthProgress,
745
+ 'error',
746
+ 'Authentication cancelled by user.',
747
+ );
748
+ return { success: false, reason: 'cancelled' };
749
+ }
750
+
751
+ continue;
752
+ }
753
+
754
+ // Handle error response
755
+ if (isErrorResponse(tokenResponse)) {
756
+ const errorData = tokenResponse as ErrorData;
757
+ throw new Error(
758
+ `Token polling failed: ${errorData?.error || 'Unknown error'} - ${errorData?.error_description || 'No details provided'}`,
759
+ );
760
+ }
761
+ } catch (error: unknown) {
762
+ // Handle specific error cases
763
+ const errorMessage =
764
+ error instanceof Error ? error.message : String(error);
765
+ const statusCode =
766
+ error instanceof Error
767
+ ? (error as Error & { status?: number }).status
768
+ : null;
769
+
770
+ if (errorMessage.includes('401') || statusCode === 401) {
771
+ const message =
772
+ 'Device code expired or invalid, please restart the authorization process.';
773
+
774
+ // Emit error event
775
+ qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, 'error', message);
776
+
777
+ return { success: false, reason: 'error' };
778
+ }
779
+
780
+ // Handle 429 Too Many Requests error
781
+ if (errorMessage.includes('429') || statusCode === 429) {
782
+ const message =
783
+ 'Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.';
784
+
785
+ // Emit rate limit event to notify user
786
+ qwenOAuth2Events.emit(
787
+ QwenOAuth2Event.AuthProgress,
788
+ 'rate_limit',
789
+ message,
790
+ );
791
+
792
+ console.log('\n' + message);
793
+
794
+ // Return false to stop polling and go back to auth selection
795
+ return { success: false, reason: 'rate_limit' };
796
+ }
797
+
798
+ const message = `Error polling for token: ${errorMessage}`;
799
+
800
+ // Emit error event
801
+ qwenOAuth2Events.emit(QwenOAuth2Event.AuthProgress, 'error', message);
802
+
803
+ // Check for cancellation before waiting
804
+ if (isCancelled) {
805
+ return { success: false, reason: 'cancelled' };
806
+ }
807
+
808
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
809
+ }
810
+ }
811
+
812
+ const timeoutMessage = 'Authorization timeout, please restart the process.';
813
+
814
+ // Emit timeout error event
815
+ qwenOAuth2Events.emit(
816
+ QwenOAuth2Event.AuthProgress,
817
+ 'timeout',
818
+ timeoutMessage,
819
+ );
820
+
821
+ console.error('\n' + timeoutMessage);
822
+ return { success: false, reason: 'timeout' };
823
+ } catch (error: unknown) {
824
+ const errorMessage = error instanceof Error ? error.message : String(error);
825
+ console.error('Device authorization flow failed:', errorMessage);
826
+ return { success: false, reason: 'error' };
827
+ } finally {
828
+ // Clean up event listener
829
+ qwenOAuth2Events.off(QwenOAuth2Event.AuthCancel, cancelHandler);
830
+ }
831
+ }
832
+
833
+ async function loadCachedQwenCredentials(
834
+ client: QwenOAuth2Client,
835
+ ): Promise<boolean> {
836
+ try {
837
+ const keyFile = getQwenCachedCredentialPath();
838
+ const creds = await fs.readFile(keyFile, 'utf-8');
839
+ const credentials = JSON.parse(creds) as QwenCredentials;
840
+ client.setCredentials(credentials);
841
+
842
+ // Verify that the credentials are still valid
843
+ const { token } = await client.getAccessToken();
844
+ if (!token) {
845
+ return false;
846
+ }
847
+
848
+ return true;
849
+ } catch (_) {
850
+ return false;
851
+ }
852
+ }
853
+
854
+ async function cacheQwenCredentials(credentials: QwenCredentials) {
855
+ const filePath = getQwenCachedCredentialPath();
856
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
857
+
858
+ const credString = JSON.stringify(credentials, null, 2);
859
+ await fs.writeFile(filePath, credString);
860
+ }
861
+
862
+ /**
863
+ * Clear cached Qwen credentials from disk
864
+ * This is useful when credentials have expired or need to be reset
865
+ */
866
+ export async function clearQwenCredentials(): Promise<void> {
867
+ try {
868
+ const filePath = getQwenCachedCredentialPath();
869
+ await fs.unlink(filePath);
870
+ console.debug('Cached Qwen credentials cleared successfully.');
871
+ } catch (error: unknown) {
872
+ // If file doesn't exist or can't be deleted, we consider it cleared
873
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
874
+ // File doesn't exist, already cleared
875
+ return;
876
+ }
877
+ // Log other errors but don't throw - clearing credentials should be non-critical
878
+ console.warn('Warning: Failed to clear cached Qwen credentials:', error);
879
+ }
880
+ }
881
+
882
+ function getQwenCachedCredentialPath(): string {
883
+ return path.join(os.homedir(), QWEN_DIR, QWEN_CREDENTIAL_FILENAME);
884
+ }
projects/ui/qwen-code/packages/core/src/qwen/sharedTokenManager.test.ts ADDED
@@ -0,0 +1,758 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ */
7
+
8
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
9
+ import { promises as fs, unlinkSync, type Stats } from 'node:fs';
10
+ import * as os from 'os';
11
+ import path from 'node:path';
12
+
13
+ import {
14
+ SharedTokenManager,
15
+ TokenManagerError,
16
+ TokenError,
17
+ } from './sharedTokenManager.js';
18
+ import type {
19
+ IQwenOAuth2Client,
20
+ QwenCredentials,
21
+ TokenRefreshData,
22
+ ErrorData,
23
+ } from './qwenOAuth2.js';
24
+
25
+ // Mock external dependencies
26
+ vi.mock('node:fs', () => ({
27
+ promises: {
28
+ stat: vi.fn(),
29
+ readFile: vi.fn(),
30
+ writeFile: vi.fn(),
31
+ mkdir: vi.fn(),
32
+ unlink: vi.fn(),
33
+ },
34
+ unlinkSync: vi.fn(),
35
+ }));
36
+
37
+ vi.mock('node:os', () => ({
38
+ homedir: vi.fn(),
39
+ }));
40
+
41
+ vi.mock('node:path', () => ({
42
+ default: {
43
+ join: vi.fn(),
44
+ dirname: vi.fn(),
45
+ },
46
+ }));
47
+
48
+ /**
49
+ * Helper to access private properties for testing
50
+ */
51
+ function getPrivateProperty<T>(obj: unknown, property: string): T {
52
+ return (obj as Record<string, T>)[property];
53
+ }
54
+
55
+ /**
56
+ * Helper to set private properties for testing
57
+ */
58
+ function setPrivateProperty<T>(obj: unknown, property: string, value: T): void {
59
+ (obj as Record<string, T>)[property] = value;
60
+ }
61
+
62
+ /**
63
+ * Creates a mock QwenOAuth2Client for testing
64
+ */
65
+ function createMockQwenClient(
66
+ initialCredentials: Partial<QwenCredentials> = {},
67
+ ): IQwenOAuth2Client {
68
+ let credentials: QwenCredentials = {
69
+ access_token: 'mock_access_token',
70
+ refresh_token: 'mock_refresh_token',
71
+ token_type: 'Bearer',
72
+ expiry_date: Date.now() + 3600000, // 1 hour from now
73
+ resource_url: 'https://api.example.com',
74
+ ...initialCredentials,
75
+ };
76
+
77
+ return {
78
+ setCredentials: vi.fn((creds: QwenCredentials) => {
79
+ credentials = { ...credentials, ...creds };
80
+ }),
81
+ getCredentials: vi.fn(() => credentials),
82
+ getAccessToken: vi.fn(),
83
+ requestDeviceAuthorization: vi.fn(),
84
+ pollDeviceToken: vi.fn(),
85
+ refreshAccessToken: vi.fn(),
86
+ };
87
+ }
88
+
89
+ /**
90
+ * Creates valid mock credentials
91
+ */
92
+ function createValidCredentials(
93
+ overrides: Partial<QwenCredentials> = {},
94
+ ): QwenCredentials {
95
+ return {
96
+ access_token: 'valid_access_token',
97
+ refresh_token: 'valid_refresh_token',
98
+ token_type: 'Bearer',
99
+ expiry_date: Date.now() + 3600000, // 1 hour from now
100
+ resource_url: 'https://api.example.com',
101
+ ...overrides,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * Creates expired mock credentials
107
+ */
108
+ function createExpiredCredentials(
109
+ overrides: Partial<QwenCredentials> = {},
110
+ ): QwenCredentials {
111
+ return {
112
+ access_token: 'expired_access_token',
113
+ refresh_token: 'expired_refresh_token',
114
+ token_type: 'Bearer',
115
+ expiry_date: Date.now() - 3600000, // 1 hour ago
116
+ resource_url: 'https://api.example.com',
117
+ ...overrides,
118
+ };
119
+ }
120
+
121
+ /**
122
+ * Creates a successful token refresh response
123
+ */
124
+ function createSuccessfulRefreshResponse(
125
+ overrides: Partial<TokenRefreshData> = {},
126
+ ): TokenRefreshData {
127
+ return {
128
+ access_token: 'fresh_access_token',
129
+ token_type: 'Bearer',
130
+ expires_in: 3600,
131
+ refresh_token: 'new_refresh_token',
132
+ resource_url: 'https://api.example.com',
133
+ ...overrides,
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Creates an error response
139
+ */
140
+ function createErrorResponse(
141
+ error = 'invalid_grant',
142
+ description = 'Token expired',
143
+ ): ErrorData {
144
+ return {
145
+ error,
146
+ error_description: description,
147
+ };
148
+ }
149
+
150
+ describe('SharedTokenManager', () => {
151
+ let tokenManager: SharedTokenManager;
152
+
153
+ // Get mocked modules
154
+ const mockFs = vi.mocked(fs);
155
+ const mockOs = vi.mocked(os);
156
+ const mockPath = vi.mocked(path);
157
+ const mockUnlinkSync = vi.mocked(unlinkSync);
158
+
159
+ beforeEach(() => {
160
+ // Clean up any existing instance's listeners first
161
+ const existingInstance = getPrivateProperty(
162
+ SharedTokenManager,
163
+ 'instance',
164
+ ) as SharedTokenManager;
165
+ if (existingInstance) {
166
+ existingInstance.cleanup();
167
+ }
168
+
169
+ // Reset all mocks
170
+ vi.clearAllMocks();
171
+
172
+ // Setup default mock implementations
173
+ mockOs.homedir.mockReturnValue('/home/user');
174
+ mockPath.join.mockImplementation((...args) => args.join('/'));
175
+ mockPath.dirname.mockImplementation((filePath) => {
176
+ // Handle undefined/null input gracefully
177
+ if (!filePath || typeof filePath !== 'string') {
178
+ return '/home/user/.qwen'; // Return the expected directory path
179
+ }
180
+ const parts = filePath.split('/');
181
+ const result = parts.slice(0, -1).join('/');
182
+ return result || '/';
183
+ });
184
+
185
+ // Reset singleton instance for each test
186
+ setPrivateProperty(SharedTokenManager, 'instance', null);
187
+ tokenManager = SharedTokenManager.getInstance();
188
+ });
189
+
190
+ afterEach(() => {
191
+ // Clean up listeners after each test
192
+ if (tokenManager) {
193
+ tokenManager.cleanup();
194
+ }
195
+ });
196
+
197
+ describe('Singleton Pattern', () => {
198
+ it('should return the same instance when called multiple times', () => {
199
+ const instance1 = SharedTokenManager.getInstance();
200
+ const instance2 = SharedTokenManager.getInstance();
201
+
202
+ expect(instance1).toBe(instance2);
203
+ expect(instance1).toBe(tokenManager);
204
+ });
205
+
206
+ it('should create a new instance after reset', () => {
207
+ const instance1 = SharedTokenManager.getInstance();
208
+
209
+ // Reset singleton for testing
210
+ setPrivateProperty(SharedTokenManager, 'instance', null);
211
+ const instance2 = SharedTokenManager.getInstance();
212
+
213
+ expect(instance1).not.toBe(instance2);
214
+ });
215
+ });
216
+
217
+ describe('getValidCredentials', () => {
218
+ it('should return valid cached credentials without refresh', async () => {
219
+ const mockClient = createMockQwenClient();
220
+ const validCredentials = createValidCredentials();
221
+
222
+ // Mock file operations to indicate no file changes
223
+ mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats);
224
+
225
+ // Manually set cached credentials
226
+ tokenManager.clearCache();
227
+ const memoryCache = getPrivateProperty<{
228
+ credentials: QwenCredentials | null;
229
+ fileModTime: number;
230
+ lastCheck: number;
231
+ }>(tokenManager, 'memoryCache');
232
+ memoryCache.credentials = validCredentials;
233
+ memoryCache.fileModTime = 1000;
234
+ memoryCache.lastCheck = Date.now();
235
+
236
+ const result = await tokenManager.getValidCredentials(mockClient);
237
+
238
+ expect(result).toEqual(validCredentials);
239
+ expect(mockClient.refreshAccessToken).not.toHaveBeenCalled();
240
+ });
241
+
242
+ it('should refresh expired credentials', async () => {
243
+ const mockClient = createMockQwenClient(createExpiredCredentials());
244
+ const refreshResponse = createSuccessfulRefreshResponse();
245
+
246
+ mockClient.refreshAccessToken = vi
247
+ .fn()
248
+ .mockResolvedValue(refreshResponse);
249
+
250
+ // Mock file operations
251
+ mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats);
252
+ mockFs.writeFile.mockResolvedValue(undefined);
253
+ mockFs.mkdir.mockResolvedValue(undefined);
254
+
255
+ const result = await tokenManager.getValidCredentials(mockClient);
256
+
257
+ expect(result.access_token).toBe(refreshResponse.access_token);
258
+ expect(mockClient.refreshAccessToken).toHaveBeenCalled();
259
+ expect(mockClient.setCredentials).toHaveBeenCalled();
260
+ });
261
+
262
+ it('should force refresh when forceRefresh is true', async () => {
263
+ const mockClient = createMockQwenClient(createValidCredentials());
264
+ const refreshResponse = createSuccessfulRefreshResponse();
265
+
266
+ mockClient.refreshAccessToken = vi
267
+ .fn()
268
+ .mockResolvedValue(refreshResponse);
269
+
270
+ // Mock file operations
271
+ mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats);
272
+ mockFs.writeFile.mockResolvedValue(undefined);
273
+ mockFs.mkdir.mockResolvedValue(undefined);
274
+
275
+ const result = await tokenManager.getValidCredentials(mockClient, true);
276
+
277
+ expect(result.access_token).toBe(refreshResponse.access_token);
278
+ expect(mockClient.refreshAccessToken).toHaveBeenCalled();
279
+ });
280
+
281
+ it('should throw TokenManagerError when refresh token is missing', async () => {
282
+ const mockClient = createMockQwenClient({
283
+ access_token: 'expired_token',
284
+ refresh_token: undefined, // No refresh token
285
+ expiry_date: Date.now() - 3600000,
286
+ });
287
+
288
+ await expect(
289
+ tokenManager.getValidCredentials(mockClient),
290
+ ).rejects.toThrow(TokenManagerError);
291
+
292
+ await expect(
293
+ tokenManager.getValidCredentials(mockClient),
294
+ ).rejects.toThrow('No refresh token available');
295
+ });
296
+
297
+ it('should throw TokenManagerError when refresh fails', async () => {
298
+ const mockClient = createMockQwenClient(createExpiredCredentials());
299
+ const errorResponse = createErrorResponse();
300
+
301
+ mockClient.refreshAccessToken = vi.fn().mockResolvedValue(errorResponse);
302
+
303
+ // Mock file operations
304
+ mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats);
305
+
306
+ await expect(
307
+ tokenManager.getValidCredentials(mockClient),
308
+ ).rejects.toThrow(TokenManagerError);
309
+ });
310
+
311
+ it('should handle network errors during refresh', async () => {
312
+ const mockClient = createMockQwenClient(createExpiredCredentials());
313
+ const networkError = new Error('Network request failed');
314
+
315
+ mockClient.refreshAccessToken = vi.fn().mockRejectedValue(networkError);
316
+
317
+ // Mock file operations
318
+ mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats);
319
+
320
+ await expect(
321
+ tokenManager.getValidCredentials(mockClient),
322
+ ).rejects.toThrow(TokenManagerError);
323
+ });
324
+
325
+ it('should wait for ongoing refresh and return same result', async () => {
326
+ const mockClient = createMockQwenClient(createExpiredCredentials());
327
+ const refreshResponse = createSuccessfulRefreshResponse();
328
+
329
+ // Create a delayed refresh response
330
+ let resolveRefresh: (value: TokenRefreshData) => void;
331
+ const refreshPromise = new Promise<TokenRefreshData>((resolve) => {
332
+ resolveRefresh = resolve;
333
+ });
334
+
335
+ mockClient.refreshAccessToken = vi.fn().mockReturnValue(refreshPromise);
336
+
337
+ // Mock file operations
338
+ mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats);
339
+ mockFs.writeFile.mockResolvedValue(undefined);
340
+ mockFs.mkdir.mockResolvedValue(undefined);
341
+
342
+ // Start two concurrent refresh operations
343
+ const promise1 = tokenManager.getValidCredentials(mockClient);
344
+ const promise2 = tokenManager.getValidCredentials(mockClient);
345
+
346
+ // Resolve the refresh
347
+ resolveRefresh!(refreshResponse);
348
+
349
+ const [result1, result2] = await Promise.all([promise1, promise2]);
350
+
351
+ expect(result1).toEqual(result2);
352
+ expect(mockClient.refreshAccessToken).toHaveBeenCalledTimes(1);
353
+ });
354
+
355
+ it('should reload credentials from file when file is modified', async () => {
356
+ const mockClient = createMockQwenClient();
357
+ const fileCredentials = createValidCredentials({
358
+ access_token: 'file_access_token',
359
+ });
360
+
361
+ // Mock file operations to simulate file modification
362
+ mockFs.stat.mockResolvedValue({ mtimeMs: 2000 } as Stats);
363
+ mockFs.readFile.mockResolvedValue(JSON.stringify(fileCredentials));
364
+
365
+ // Set initial cache state
366
+ tokenManager.clearCache();
367
+ const memoryCache = getPrivateProperty<{ fileModTime: number }>(
368
+ tokenManager,
369
+ 'memoryCache',
370
+ );
371
+ memoryCache.fileModTime = 1000; // Older than file
372
+
373
+ const result = await tokenManager.getValidCredentials(mockClient);
374
+
375
+ expect(result.access_token).toBe('file_access_token');
376
+ expect(mockFs.readFile).toHaveBeenCalled();
377
+ });
378
+ });
379
+
380
+ describe('Cache Management', () => {
381
+ it('should clear cache', () => {
382
+ // Set some cache data
383
+ tokenManager.clearCache();
384
+ const memoryCache = getPrivateProperty<{
385
+ credentials: QwenCredentials | null;
386
+ }>(tokenManager, 'memoryCache');
387
+ memoryCache.credentials = createValidCredentials();
388
+
389
+ tokenManager.clearCache();
390
+
391
+ expect(tokenManager.getCurrentCredentials()).toBeNull();
392
+ });
393
+
394
+ it('should return current credentials from cache', () => {
395
+ const credentials = createValidCredentials();
396
+
397
+ tokenManager.clearCache();
398
+ const memoryCache = getPrivateProperty<{
399
+ credentials: QwenCredentials | null;
400
+ }>(tokenManager, 'memoryCache');
401
+ memoryCache.credentials = credentials;
402
+
403
+ expect(tokenManager.getCurrentCredentials()).toEqual(credentials);
404
+ });
405
+
406
+ it('should return null when no credentials are cached', () => {
407
+ tokenManager.clearCache();
408
+
409
+ expect(tokenManager.getCurrentCredentials()).toBeNull();
410
+ });
411
+ });
412
+
413
+ describe('Refresh Status', () => {
414
+ it('should return false when no refresh is in progress', () => {
415
+ expect(tokenManager.isRefreshInProgress()).toBe(false);
416
+ });
417
+
418
+ it('should return true when refresh is in progress', async () => {
419
+ const mockClient = createMockQwenClient(createExpiredCredentials());
420
+
421
+ // Clear cache to ensure refresh is triggered
422
+ tokenManager.clearCache();
423
+
424
+ // Mock stat for file check to fail (no file initially)
425
+ mockFs.stat.mockRejectedValueOnce(
426
+ Object.assign(new Error('ENOENT'), { code: 'ENOENT' }),
427
+ );
428
+
429
+ // Create a delayed refresh response
430
+ let resolveRefresh: (value: TokenRefreshData) => void;
431
+ const refreshPromise = new Promise<TokenRefreshData>((resolve) => {
432
+ resolveRefresh = resolve;
433
+ });
434
+
435
+ mockClient.refreshAccessToken = vi.fn().mockReturnValue(refreshPromise);
436
+
437
+ // Mock file operations for lock and save
438
+ mockFs.writeFile.mockResolvedValue(undefined);
439
+ mockFs.mkdir.mockResolvedValue(undefined);
440
+ mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats);
441
+
442
+ // Start refresh
443
+ const refreshOperation = tokenManager.getValidCredentials(mockClient);
444
+
445
+ // Wait a tick to ensure the refresh promise is set
446
+ await new Promise((resolve) => setImmediate(resolve));
447
+
448
+ expect(tokenManager.isRefreshInProgress()).toBe(true);
449
+
450
+ // Complete refresh
451
+ resolveRefresh!(createSuccessfulRefreshResponse());
452
+ await refreshOperation;
453
+
454
+ expect(tokenManager.isRefreshInProgress()).toBe(false);
455
+ });
456
+ });
457
+
458
+ describe('Debug Info', () => {
459
+ it('should return complete debug information', () => {
460
+ const credentials = createValidCredentials();
461
+
462
+ tokenManager.clearCache();
463
+ const memoryCache = getPrivateProperty<{
464
+ credentials: QwenCredentials | null;
465
+ }>(tokenManager, 'memoryCache');
466
+ memoryCache.credentials = credentials;
467
+
468
+ const debugInfo = tokenManager.getDebugInfo();
469
+
470
+ expect(debugInfo).toHaveProperty('hasCredentials', true);
471
+ expect(debugInfo).toHaveProperty('credentialsExpired', false);
472
+ expect(debugInfo).toHaveProperty('isRefreshing', false);
473
+ expect(debugInfo).toHaveProperty('cacheAge');
474
+ expect(typeof debugInfo.cacheAge).toBe('number');
475
+ });
476
+
477
+ it('should indicate expired credentials in debug info', () => {
478
+ const expiredCredentials = createExpiredCredentials();
479
+
480
+ tokenManager.clearCache();
481
+ const memoryCache = getPrivateProperty<{
482
+ credentials: QwenCredentials | null;
483
+ }>(tokenManager, 'memoryCache');
484
+ memoryCache.credentials = expiredCredentials;
485
+
486
+ const debugInfo = tokenManager.getDebugInfo();
487
+
488
+ expect(debugInfo.hasCredentials).toBe(true);
489
+ expect(debugInfo.credentialsExpired).toBe(true);
490
+ });
491
+
492
+ it('should indicate no credentials in debug info', () => {
493
+ tokenManager.clearCache();
494
+
495
+ const debugInfo = tokenManager.getDebugInfo();
496
+
497
+ expect(debugInfo.hasCredentials).toBe(false);
498
+ expect(debugInfo.credentialsExpired).toBe(false);
499
+ });
500
+ });
501
+
502
+ describe('Error Handling', () => {
503
+ it('should create TokenManagerError with correct type and message', () => {
504
+ const error = new TokenManagerError(
505
+ TokenError.REFRESH_FAILED,
506
+ 'Token refresh failed',
507
+ new Error('Original error'),
508
+ );
509
+
510
+ expect(error).toBeInstanceOf(Error);
511
+ expect(error).toBeInstanceOf(TokenManagerError);
512
+ expect(error.type).toBe(TokenError.REFRESH_FAILED);
513
+ expect(error.message).toBe('Token refresh failed');
514
+ expect(error.name).toBe('TokenManagerError');
515
+ expect(error.originalError).toBeInstanceOf(Error);
516
+ });
517
+
518
+ it('should handle file access errors gracefully', async () => {
519
+ const mockClient = createMockQwenClient(createExpiredCredentials());
520
+
521
+ // Mock file stat to throw access error
522
+ const accessError = new Error(
523
+ 'Permission denied',
524
+ ) as NodeJS.ErrnoException;
525
+ accessError.code = 'EACCES';
526
+ mockFs.stat.mockRejectedValue(accessError);
527
+
528
+ await expect(
529
+ tokenManager.getValidCredentials(mockClient),
530
+ ).rejects.toThrow(TokenManagerError);
531
+ });
532
+
533
+ it('should handle missing file gracefully', async () => {
534
+ const mockClient = createMockQwenClient();
535
+ const validCredentials = createValidCredentials();
536
+
537
+ // Mock file stat to throw file not found error
538
+ const notFoundError = new Error(
539
+ 'File not found',
540
+ ) as NodeJS.ErrnoException;
541
+ notFoundError.code = 'ENOENT';
542
+ mockFs.stat.mockRejectedValue(notFoundError);
543
+
544
+ // Set valid credentials in cache
545
+ const memoryCache = getPrivateProperty<{
546
+ credentials: QwenCredentials | null;
547
+ }>(tokenManager, 'memoryCache');
548
+ memoryCache.credentials = validCredentials;
549
+
550
+ const result = await tokenManager.getValidCredentials(mockClient);
551
+
552
+ expect(result).toEqual(validCredentials);
553
+ });
554
+
555
+ it('should handle lock timeout scenarios', async () => {
556
+ const mockClient = createMockQwenClient(createExpiredCredentials());
557
+
558
+ // Configure shorter timeouts for testing
559
+ tokenManager.setLockConfig({
560
+ maxAttempts: 3,
561
+ attemptInterval: 50,
562
+ });
563
+
564
+ // Mock stat for file check to pass (no file initially)
565
+ mockFs.stat.mockRejectedValueOnce(
566
+ Object.assign(new Error('ENOENT'), { code: 'ENOENT' }),
567
+ );
568
+
569
+ // Mock writeFile to always throw EEXIST for lock file writes (flag: 'wx')
570
+ // but succeed for regular file writes
571
+ const lockError = new Error('File exists') as NodeJS.ErrnoException;
572
+ lockError.code = 'EEXIST';
573
+
574
+ mockFs.writeFile.mockImplementation((path, data, options) => {
575
+ if (typeof options === 'object' && options?.flag === 'wx') {
576
+ return Promise.reject(lockError);
577
+ }
578
+ return Promise.resolve(undefined);
579
+ });
580
+
581
+ // Mock stat to return recent lock file (not stale) when checking lock age
582
+ mockFs.stat.mockResolvedValue({ mtimeMs: Date.now() } as Stats);
583
+
584
+ // Mock unlink to simulate lock file removal attempts
585
+ mockFs.unlink.mockResolvedValue(undefined);
586
+
587
+ await expect(
588
+ tokenManager.getValidCredentials(mockClient),
589
+ ).rejects.toThrow(TokenManagerError);
590
+ }, 500); // 500ms timeout for lock test (3 attempts × 50ms = ~150ms + buffer)
591
+
592
+ it('should handle refresh response without access token', async () => {
593
+ const mockClient = createMockQwenClient(createExpiredCredentials());
594
+ const invalidResponse = {
595
+ token_type: 'Bearer',
596
+ expires_in: 3600,
597
+ // access_token is missing, so we use undefined explicitly
598
+ access_token: undefined,
599
+ } as Partial<TokenRefreshData>;
600
+
601
+ mockClient.refreshAccessToken = vi
602
+ .fn()
603
+ .mockResolvedValue(invalidResponse);
604
+
605
+ // Mock stat for file check to pass (no file initially)
606
+ mockFs.stat.mockRejectedValueOnce(
607
+ Object.assign(new Error('ENOENT'), { code: 'ENOENT' }),
608
+ );
609
+
610
+ // Mock file operations for lock acquisition
611
+ mockFs.writeFile.mockResolvedValue(undefined);
612
+ mockFs.mkdir.mockResolvedValue(undefined);
613
+
614
+ // Clear cache to force refresh
615
+ tokenManager.clearCache();
616
+
617
+ await expect(
618
+ tokenManager.getValidCredentials(mockClient),
619
+ ).rejects.toThrow(TokenManagerError);
620
+
621
+ await expect(
622
+ tokenManager.getValidCredentials(mockClient),
623
+ ).rejects.toThrow('no token returned');
624
+ });
625
+ });
626
+
627
+ describe('File System Operations', () => {
628
+ it('should handle file reload failures gracefully', async () => {
629
+ const mockClient = createMockQwenClient();
630
+
631
+ // Mock successful refresh for when cache is cleared
632
+ mockClient.refreshAccessToken = vi
633
+ .fn()
634
+ .mockResolvedValue(createSuccessfulRefreshResponse());
635
+
636
+ // Mock file operations
637
+ mockFs.stat
638
+ .mockResolvedValueOnce({ mtimeMs: 2000 } as Stats) // For checkAndReloadIfNeeded
639
+ .mockResolvedValue({ mtimeMs: 1000 } as Stats); // For later operations
640
+ mockFs.readFile.mockRejectedValue(new Error('Read failed'));
641
+ mockFs.writeFile.mockResolvedValue(undefined);
642
+ mockFs.mkdir.mockResolvedValue(undefined);
643
+
644
+ // Set initial cache state to trigger reload
645
+ tokenManager.clearCache();
646
+ const memoryCache = getPrivateProperty<{ fileModTime: number }>(
647
+ tokenManager,
648
+ 'memoryCache',
649
+ );
650
+ memoryCache.fileModTime = 1000;
651
+
652
+ // Should not throw error, should refresh and get new credentials
653
+ const result = await tokenManager.getValidCredentials(mockClient);
654
+
655
+ expect(result).toBeDefined();
656
+ expect(result.access_token).toBe('fresh_access_token');
657
+ });
658
+
659
+ it('should handle invalid JSON in credentials file', async () => {
660
+ const mockClient = createMockQwenClient();
661
+
662
+ // Mock successful refresh for when cache is cleared
663
+ mockClient.refreshAccessToken = vi
664
+ .fn()
665
+ .mockResolvedValue(createSuccessfulRefreshResponse());
666
+
667
+ // Mock file operations with invalid JSON
668
+ mockFs.stat
669
+ .mockResolvedValueOnce({ mtimeMs: 2000 } as Stats) // For checkAndReloadIfNeeded
670
+ .mockResolvedValue({ mtimeMs: 1000 } as Stats); // For later operations
671
+ mockFs.readFile.mockResolvedValue('invalid json content');
672
+ mockFs.writeFile.mockResolvedValue(undefined);
673
+ mockFs.mkdir.mockResolvedValue(undefined);
674
+
675
+ // Set initial cache state to trigger reload
676
+ tokenManager.clearCache();
677
+ const memoryCache = getPrivateProperty<{ fileModTime: number }>(
678
+ tokenManager,
679
+ 'memoryCache',
680
+ );
681
+ memoryCache.fileModTime = 1000;
682
+
683
+ // Should handle JSON parse error gracefully, then refresh and get new credentials
684
+ const result = await tokenManager.getValidCredentials(mockClient);
685
+
686
+ expect(result).toBeDefined();
687
+ expect(result.access_token).toBe('fresh_access_token');
688
+ });
689
+
690
+ it('should handle directory creation during save', async () => {
691
+ const mockClient = createMockQwenClient(createExpiredCredentials());
692
+ const refreshResponse = createSuccessfulRefreshResponse();
693
+
694
+ mockClient.refreshAccessToken = vi
695
+ .fn()
696
+ .mockResolvedValue(refreshResponse);
697
+
698
+ // Mock file operations
699
+ mockFs.stat.mockResolvedValue({ mtimeMs: 1000 } as Stats);
700
+ mockFs.writeFile.mockResolvedValue(undefined);
701
+ mockFs.mkdir.mockResolvedValue(undefined);
702
+
703
+ await tokenManager.getValidCredentials(mockClient);
704
+
705
+ expect(mockFs.mkdir).toHaveBeenCalledWith(expect.any(String), {
706
+ recursive: true,
707
+ mode: 0o700,
708
+ });
709
+ expect(mockFs.writeFile).toHaveBeenCalled();
710
+ });
711
+ });
712
+
713
+ describe('Lock File Management', () => {
714
+ it('should clean up lock file during process cleanup', () => {
715
+ // Create a new instance to trigger cleanup handler registration
716
+ SharedTokenManager.getInstance();
717
+
718
+ // Access the private cleanup method for testing
719
+ const cleanupHandlers = process.listeners('exit');
720
+ const cleanup = cleanupHandlers[cleanupHandlers.length - 1] as () => void;
721
+
722
+ // Should not throw when lock file doesn't exist
723
+ expect(() => cleanup()).not.toThrow();
724
+ expect(mockUnlinkSync).toHaveBeenCalled();
725
+ });
726
+
727
+ it('should handle stale lock cleanup', async () => {
728
+ const mockClient = createMockQwenClient(createExpiredCredentials());
729
+ const refreshResponse = createSuccessfulRefreshResponse();
730
+
731
+ mockClient.refreshAccessToken = vi
732
+ .fn()
733
+ .mockResolvedValue(refreshResponse);
734
+
735
+ // First writeFile call throws EEXIST (lock exists)
736
+ // Second writeFile call succeeds (after stale lock cleanup)
737
+ const lockError = new Error('File exists') as NodeJS.ErrnoException;
738
+ lockError.code = 'EEXIST';
739
+ mockFs.writeFile
740
+ .mockRejectedValueOnce(lockError)
741
+ .mockResolvedValue(undefined);
742
+
743
+ // Mock stat to return stale lock (old timestamp)
744
+ mockFs.stat
745
+ .mockResolvedValueOnce({ mtimeMs: Date.now() - 20000 } as Stats) // Stale lock
746
+ .mockResolvedValueOnce({ mtimeMs: 1000 } as Stats); // Credentials file
747
+
748
+ // Mock unlink to succeed
749
+ mockFs.unlink.mockResolvedValue(undefined);
750
+ mockFs.mkdir.mockResolvedValue(undefined);
751
+
752
+ const result = await tokenManager.getValidCredentials(mockClient);
753
+
754
+ expect(result.access_token).toBe(refreshResponse.access_token);
755
+ expect(mockFs.unlink).toHaveBeenCalled(); // Stale lock removed
756
+ });
757
+ });
758
+ });
projects/ui/qwen-code/packages/core/src/qwen/sharedTokenManager.ts ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Qwen
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import path from 'node:path';
8
+ import { promises as fs, unlinkSync } from 'node:fs';
9
+ import * as os from 'os';
10
+ import { randomUUID } from 'node:crypto';
11
+
12
+ import {
13
+ IQwenOAuth2Client,
14
+ type QwenCredentials,
15
+ type TokenRefreshData,
16
+ type ErrorData,
17
+ isErrorResponse,
18
+ } from './qwenOAuth2.js';
19
+
20
+ // File System Configuration
21
+ const QWEN_DIR = '.qwen';
22
+ const QWEN_CREDENTIAL_FILENAME = 'oauth_creds.json';
23
+ const QWEN_LOCK_FILENAME = 'oauth_creds.lock';
24
+
25
+ // Token and Cache Configuration
26
+ const TOKEN_REFRESH_BUFFER_MS = 30 * 1000; // 30 seconds
27
+ const LOCK_TIMEOUT_MS = 10000; // 10 seconds lock timeout
28
+ const CACHE_CHECK_INTERVAL_MS = 1000; // 1 second cache check interval
29
+
30
+ // Lock acquisition configuration (can be overridden for testing)
31
+ interface LockConfig {
32
+ maxAttempts: number;
33
+ attemptInterval: number;
34
+ }
35
+
36
+ const DEFAULT_LOCK_CONFIG: LockConfig = {
37
+ maxAttempts: 50,
38
+ attemptInterval: 200,
39
+ };
40
+
41
+ /**
42
+ * Token manager error types for better error classification
43
+ */
44
+ export enum TokenError {
45
+ REFRESH_FAILED = 'REFRESH_FAILED',
46
+ NO_REFRESH_TOKEN = 'NO_REFRESH_TOKEN',
47
+ LOCK_TIMEOUT = 'LOCK_TIMEOUT',
48
+ FILE_ACCESS_ERROR = 'FILE_ACCESS_ERROR',
49
+ NETWORK_ERROR = 'NETWORK_ERROR',
50
+ }
51
+
52
+ /**
53
+ * Custom error class for token manager operations
54
+ */
55
+ export class TokenManagerError extends Error {
56
+ constructor(
57
+ public type: TokenError,
58
+ message: string,
59
+ public originalError?: unknown,
60
+ ) {
61
+ super(message);
62
+ this.name = 'TokenManagerError';
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Interface for the memory cache state
68
+ */
69
+ interface MemoryCache {
70
+ credentials: QwenCredentials | null;
71
+ fileModTime: number;
72
+ lastCheck: number;
73
+ }
74
+
75
+ /**
76
+ * Validates that the given data is a valid QwenCredentials object
77
+ *
78
+ * @param data - The data to validate
79
+ * @returns The validated credentials object
80
+ * @throws Error if the data is invalid
81
+ */
82
+ function validateCredentials(data: unknown): QwenCredentials {
83
+ if (!data || typeof data !== 'object') {
84
+ throw new Error('Invalid credentials format');
85
+ }
86
+
87
+ const creds = data as Partial<QwenCredentials>;
88
+ const requiredFields = [
89
+ 'access_token',
90
+ 'refresh_token',
91
+ 'token_type',
92
+ ] as const;
93
+
94
+ // Check required string fields
95
+ for (const field of requiredFields) {
96
+ if (!creds[field] || typeof creds[field] !== 'string') {
97
+ throw new Error(`Invalid credentials: missing ${field}`);
98
+ }
99
+ }
100
+
101
+ // Check expiry_date
102
+ if (!creds.expiry_date || typeof creds.expiry_date !== 'number') {
103
+ throw new Error('Invalid credentials: missing expiry_date');
104
+ }
105
+
106
+ return creds as QwenCredentials;
107
+ }
108
+
109
+ /**
110
+ * Manages OAuth tokens across multiple processes using file-based caching and locking
111
+ */
112
+ export class SharedTokenManager {
113
+ private static instance: SharedTokenManager | null = null;
114
+
115
+ /**
116
+ * In-memory cache for credentials and file state tracking
117
+ */
118
+ private memoryCache: MemoryCache = {
119
+ credentials: null,
120
+ fileModTime: 0,
121
+ lastCheck: 0,
122
+ };
123
+
124
+ /**
125
+ * Promise tracking any ongoing token refresh operation
126
+ */
127
+ private refreshPromise: Promise<QwenCredentials> | null = null;
128
+
129
+ /**
130
+ * Whether cleanup handlers have been registered
131
+ */
132
+ private cleanupHandlersRegistered = false;
133
+
134
+ /**
135
+ * Reference to cleanup functions for proper removal
136
+ */
137
+ private cleanupFunction: (() => void) | null = null;
138
+
139
+ /**
140
+ * Lock configuration for testing purposes
141
+ */
142
+ private lockConfig: LockConfig = DEFAULT_LOCK_CONFIG;
143
+
144
+ /**
145
+ * Private constructor for singleton pattern
146
+ */
147
+ private constructor() {
148
+ this.registerCleanupHandlers();
149
+ }
150
+
151
+ /**
152
+ * Get the singleton instance
153
+ * @returns The shared token manager instance
154
+ */
155
+ static getInstance(): SharedTokenManager {
156
+ if (!SharedTokenManager.instance) {
157
+ SharedTokenManager.instance = new SharedTokenManager();
158
+ }
159
+ return SharedTokenManager.instance;
160
+ }
161
+
162
+ /**
163
+ * Set up handlers to clean up lock files when the process exits
164
+ */
165
+ private registerCleanupHandlers(): void {
166
+ if (this.cleanupHandlersRegistered) {
167
+ return;
168
+ }
169
+
170
+ this.cleanupFunction = () => {
171
+ try {
172
+ const lockPath = this.getLockFilePath();
173
+ // Use synchronous unlink for process exit handlers
174
+ unlinkSync(lockPath);
175
+ } catch (_error) {
176
+ // Ignore cleanup errors - lock file might not exist or already be cleaned up
177
+ }
178
+ };
179
+
180
+ process.on('exit', this.cleanupFunction);
181
+ process.on('SIGINT', this.cleanupFunction);
182
+ process.on('SIGTERM', this.cleanupFunction);
183
+ process.on('uncaughtException', this.cleanupFunction);
184
+ process.on('unhandledRejection', this.cleanupFunction);
185
+
186
+ this.cleanupHandlersRegistered = true;
187
+ }
188
+
189
+ /**
190
+ * Get valid OAuth credentials, refreshing them if necessary
191
+ *
192
+ * @param qwenClient - The OAuth2 client instance
193
+ * @param forceRefresh - If true, refresh token even if current one is still valid
194
+ * @returns Promise resolving to valid credentials
195
+ * @throws TokenManagerError if unable to obtain valid credentials
196
+ */
197
+ async getValidCredentials(
198
+ qwenClient: IQwenOAuth2Client,
199
+ forceRefresh = false,
200
+ ): Promise<QwenCredentials> {
201
+ try {
202
+ // Check if credentials file has been updated by other sessions
203
+ await this.checkAndReloadIfNeeded();
204
+
205
+ // Return valid cached credentials if available (unless force refresh is requested)
206
+ if (
207
+ !forceRefresh &&
208
+ this.memoryCache.credentials &&
209
+ this.isTokenValid(this.memoryCache.credentials)
210
+ ) {
211
+ return this.memoryCache.credentials;
212
+ }
213
+
214
+ // If refresh is already in progress, wait for it to complete
215
+ if (this.refreshPromise) {
216
+ return this.refreshPromise;
217
+ }
218
+
219
+ // Start new refresh operation with distributed locking
220
+ this.refreshPromise = this.performTokenRefresh(qwenClient, forceRefresh);
221
+
222
+ try {
223
+ const credentials = await this.refreshPromise;
224
+ return credentials;
225
+ } catch (error) {
226
+ // Ensure refreshPromise is cleared on error before re-throwing
227
+ this.refreshPromise = null;
228
+ throw error;
229
+ } finally {
230
+ this.refreshPromise = null;
231
+ }
232
+ } catch (error) {
233
+ // Convert generic errors to TokenManagerError for better error handling
234
+ if (error instanceof TokenManagerError) {
235
+ throw error;
236
+ }
237
+
238
+ throw new TokenManagerError(
239
+ TokenError.REFRESH_FAILED,
240
+ `Failed to get valid credentials: ${error instanceof Error ? error.message : String(error)}`,
241
+ error,
242
+ );
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Check if the credentials file was updated by another process and reload if so
248
+ */
249
+ private async checkAndReloadIfNeeded(): Promise<void> {
250
+ const now = Date.now();
251
+
252
+ // Limit check frequency to avoid excessive disk I/O
253
+ if (now - this.memoryCache.lastCheck < CACHE_CHECK_INTERVAL_MS) {
254
+ return;
255
+ }
256
+
257
+ this.memoryCache.lastCheck = now;
258
+
259
+ try {
260
+ const filePath = this.getCredentialFilePath();
261
+ const stats = await fs.stat(filePath);
262
+ const fileModTime = stats.mtimeMs;
263
+
264
+ // Reload credentials if file has been modified since last cache
265
+ if (fileModTime > this.memoryCache.fileModTime) {
266
+ await this.reloadCredentialsFromFile();
267
+ this.memoryCache.fileModTime = fileModTime;
268
+ }
269
+ } catch (error) {
270
+ // Handle file access errors
271
+ if (
272
+ error instanceof Error &&
273
+ 'code' in error &&
274
+ error.code !== 'ENOENT'
275
+ ) {
276
+ // Clear cache for non-missing file errors
277
+ this.memoryCache.credentials = null;
278
+ this.memoryCache.fileModTime = 0;
279
+
280
+ throw new TokenManagerError(
281
+ TokenError.FILE_ACCESS_ERROR,
282
+ `Failed to access credentials file: ${error.message}`,
283
+ error,
284
+ );
285
+ }
286
+
287
+ // For missing files (ENOENT), just reset file modification time
288
+ // but keep existing valid credentials in memory if they exist
289
+ this.memoryCache.fileModTime = 0;
290
+ }
291
+ }
292
+
293
+ /**
294
+ * Load credentials from the file system into memory cache
295
+ */
296
+ private async reloadCredentialsFromFile(): Promise<void> {
297
+ try {
298
+ const filePath = this.getCredentialFilePath();
299
+ const content = await fs.readFile(filePath, 'utf-8');
300
+ const parsedData = JSON.parse(content);
301
+ const credentials = validateCredentials(parsedData);
302
+ this.memoryCache.credentials = credentials;
303
+ } catch (error) {
304
+ // Log validation errors for debugging but don't throw
305
+ if (
306
+ error instanceof Error &&
307
+ error.message.includes('Invalid credentials')
308
+ ) {
309
+ console.warn(`Failed to validate credentials file: ${error.message}`);
310
+ }
311
+ this.memoryCache.credentials = null;
312
+ }
313
+ }
314
+
315
+ /**
316
+ * Refresh the OAuth token using file locking to prevent concurrent refreshes
317
+ *
318
+ * @param qwenClient - The OAuth2 client instance
319
+ * @param forceRefresh - If true, skip checking if token is already valid after getting lock
320
+ * @returns Promise resolving to refreshed credentials
321
+ * @throws TokenManagerError if refresh fails or lock cannot be acquired
322
+ */
323
+ private async performTokenRefresh(
324
+ qwenClient: IQwenOAuth2Client,
325
+ forceRefresh = false,
326
+ ): Promise<QwenCredentials> {
327
+ const lockPath = this.getLockFilePath();
328
+
329
+ try {
330
+ // Check if we have a refresh token before attempting refresh
331
+ const currentCredentials = qwenClient.getCredentials();
332
+ if (!currentCredentials.refresh_token) {
333
+ throw new TokenManagerError(
334
+ TokenError.NO_REFRESH_TOKEN,
335
+ 'No refresh token available for token refresh',
336
+ );
337
+ }
338
+
339
+ // Acquire distributed file lock
340
+ await this.acquireLock(lockPath);
341
+
342
+ // Double-check if another process already refreshed the token (unless force refresh is requested)
343
+ await this.checkAndReloadIfNeeded();
344
+
345
+ // Use refreshed credentials if they're now valid (unless force refresh is requested)
346
+ if (
347
+ !forceRefresh &&
348
+ this.memoryCache.credentials &&
349
+ this.isTokenValid(this.memoryCache.credentials)
350
+ ) {
351
+ qwenClient.setCredentials(this.memoryCache.credentials);
352
+ return this.memoryCache.credentials;
353
+ }
354
+
355
+ // Perform the actual token refresh
356
+ const response = await qwenClient.refreshAccessToken();
357
+
358
+ if (!response || isErrorResponse(response)) {
359
+ const errorData = response as ErrorData;
360
+ throw new TokenManagerError(
361
+ TokenError.REFRESH_FAILED,
362
+ `Token refresh failed: ${errorData?.error || 'Unknown error'} - ${errorData?.error_description || 'No details provided'}`,
363
+ );
364
+ }
365
+
366
+ const tokenData = response as TokenRefreshData;
367
+
368
+ if (!tokenData.access_token) {
369
+ throw new TokenManagerError(
370
+ TokenError.REFRESH_FAILED,
371
+ 'Failed to refresh access token: no token returned',
372
+ );
373
+ }
374
+
375
+ // Create updated credentials object
376
+ const credentials: QwenCredentials = {
377
+ access_token: tokenData.access_token,
378
+ token_type: tokenData.token_type,
379
+ refresh_token:
380
+ tokenData.refresh_token || currentCredentials.refresh_token,
381
+ resource_url: tokenData.resource_url,
382
+ expiry_date: Date.now() + tokenData.expires_in * 1000,
383
+ };
384
+
385
+ // Update memory cache and client credentials
386
+ this.memoryCache.credentials = credentials;
387
+ qwenClient.setCredentials(credentials);
388
+
389
+ // Persist to file and update modification time
390
+ await this.saveCredentialsToFile(credentials);
391
+
392
+ return credentials;
393
+ } catch (error) {
394
+ if (error instanceof TokenManagerError) {
395
+ throw error;
396
+ }
397
+
398
+ // Handle network-related errors
399
+ if (
400
+ error instanceof Error &&
401
+ (error.message.includes('fetch') ||
402
+ error.message.includes('network') ||
403
+ error.message.includes('timeout'))
404
+ ) {
405
+ throw new TokenManagerError(
406
+ TokenError.NETWORK_ERROR,
407
+ `Network error during token refresh: ${error.message}`,
408
+ error,
409
+ );
410
+ }
411
+
412
+ throw new TokenManagerError(
413
+ TokenError.REFRESH_FAILED,
414
+ `Unexpected error during token refresh: ${error instanceof Error ? error.message : String(error)}`,
415
+ error,
416
+ );
417
+ } finally {
418
+ // Always release the file lock
419
+ await this.releaseLock(lockPath);
420
+ }
421
+ }
422
+
423
+ /**
424
+ * Save credentials to file and update the cached file modification time
425
+ *
426
+ * @param credentials - The credentials to save
427
+ */
428
+ private async saveCredentialsToFile(
429
+ credentials: QwenCredentials,
430
+ ): Promise<void> {
431
+ const filePath = this.getCredentialFilePath();
432
+ const dirPath = path.dirname(filePath);
433
+
434
+ // Create directory with restricted permissions
435
+ try {
436
+ await fs.mkdir(dirPath, { recursive: true, mode: 0o700 });
437
+ } catch (error) {
438
+ throw new TokenManagerError(
439
+ TokenError.FILE_ACCESS_ERROR,
440
+ `Failed to create credentials directory: ${error instanceof Error ? error.message : String(error)}`,
441
+ error,
442
+ );
443
+ }
444
+
445
+ const credString = JSON.stringify(credentials, null, 2);
446
+
447
+ try {
448
+ // Write file with restricted permissions (owner read/write only)
449
+ await fs.writeFile(filePath, credString, { mode: 0o600 });
450
+ } catch (error) {
451
+ throw new TokenManagerError(
452
+ TokenError.FILE_ACCESS_ERROR,
453
+ `Failed to write credentials file: ${error instanceof Error ? error.message : String(error)}`,
454
+ error,
455
+ );
456
+ }
457
+
458
+ // Update cached file modification time to avoid unnecessary reloads
459
+ try {
460
+ const stats = await fs.stat(filePath);
461
+ this.memoryCache.fileModTime = stats.mtimeMs;
462
+ } catch (error) {
463
+ // Non-fatal error, just log it
464
+ console.warn(
465
+ `Failed to update file modification time: ${error instanceof Error ? error.message : String(error)}`,
466
+ );
467
+ }
468
+ }
469
+
470
+ /**
471
+ * Check if the token is valid and not expired
472
+ *
473
+ * @param credentials - The credentials to validate
474
+ * @returns true if token is valid and not expired, false otherwise
475
+ */
476
+ private isTokenValid(credentials: QwenCredentials): boolean {
477
+ if (!credentials.expiry_date || !credentials.access_token) {
478
+ return false;
479
+ }
480
+ return Date.now() < credentials.expiry_date - TOKEN_REFRESH_BUFFER_MS;
481
+ }
482
+
483
+ /**
484
+ * Get the full path to the credentials file
485
+ *
486
+ * @returns The absolute path to the credentials file
487
+ */
488
+ private getCredentialFilePath(): string {
489
+ return path.join(os.homedir(), QWEN_DIR, QWEN_CREDENTIAL_FILENAME);
490
+ }
491
+
492
+ /**
493
+ * Get the full path to the lock file
494
+ *
495
+ * @returns The absolute path to the lock file
496
+ */
497
+ private getLockFilePath(): string {
498
+ return path.join(os.homedir(), QWEN_DIR, QWEN_LOCK_FILENAME);
499
+ }
500
+
501
+ /**
502
+ * Acquire a file lock to prevent other processes from refreshing tokens simultaneously
503
+ *
504
+ * @param lockPath - Path to the lock file
505
+ * @throws TokenManagerError if lock cannot be acquired within timeout period
506
+ */
507
+ private async acquireLock(lockPath: string): Promise<void> {
508
+ const { maxAttempts, attemptInterval } = this.lockConfig;
509
+ const lockId = randomUUID(); // Use random UUID instead of PID for security
510
+
511
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
512
+ try {
513
+ // Attempt to create lock file atomically (exclusive mode)
514
+ await fs.writeFile(lockPath, lockId, { flag: 'wx' });
515
+ return; // Successfully acquired lock
516
+ } catch (error: unknown) {
517
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
518
+ // Lock file already exists, check if it's stale
519
+ try {
520
+ const stats = await fs.stat(lockPath);
521
+ const lockAge = Date.now() - stats.mtimeMs;
522
+
523
+ // Remove stale locks that exceed timeout
524
+ if (lockAge > LOCK_TIMEOUT_MS) {
525
+ try {
526
+ await fs.unlink(lockPath);
527
+ console.warn(
528
+ `Removed stale lock file: ${lockPath} (age: ${lockAge}ms)`,
529
+ );
530
+ continue; // Retry lock acquisition
531
+ } catch (unlinkError) {
532
+ // Log the error but continue trying - another process might have removed it
533
+ console.warn(
534
+ `Failed to remove stale lock file ${lockPath}: ${unlinkError instanceof Error ? unlinkError.message : String(unlinkError)}`,
535
+ );
536
+ // Still continue - the lock might have been removed by another process
537
+ }
538
+ }
539
+ } catch (statError) {
540
+ // Can't stat lock file, it might have been removed, continue trying
541
+ console.warn(
542
+ `Failed to stat lock file ${lockPath}: ${statError instanceof Error ? statError.message : String(statError)}`,
543
+ );
544
+ }
545
+
546
+ // Wait before retrying
547
+ await new Promise((resolve) => setTimeout(resolve, attemptInterval));
548
+ } else {
549
+ throw new TokenManagerError(
550
+ TokenError.FILE_ACCESS_ERROR,
551
+ `Failed to create lock file: ${error instanceof Error ? error.message : String(error)}`,
552
+ error,
553
+ );
554
+ }
555
+ }
556
+ }
557
+
558
+ throw new TokenManagerError(
559
+ TokenError.LOCK_TIMEOUT,
560
+ 'Failed to acquire file lock for token refresh: timeout exceeded',
561
+ );
562
+ }
563
+
564
+ /**
565
+ * Release the file lock
566
+ *
567
+ * @param lockPath - Path to the lock file
568
+ */
569
+ private async releaseLock(lockPath: string): Promise<void> {
570
+ try {
571
+ await fs.unlink(lockPath);
572
+ } catch (error) {
573
+ // Lock file might already be removed by another process or timeout cleanup
574
+ // This is not an error condition, but log for debugging
575
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
576
+ console.warn(
577
+ `Failed to release lock file ${lockPath}: ${error instanceof Error ? error.message : String(error)}`,
578
+ );
579
+ }
580
+ }
581
+ }
582
+
583
+ /**
584
+ * Clear all cached data and reset the manager to initial state
585
+ */
586
+ clearCache(): void {
587
+ this.memoryCache = {
588
+ credentials: null,
589
+ fileModTime: 0,
590
+ lastCheck: 0,
591
+ };
592
+ this.refreshPromise = null;
593
+ }
594
+
595
+ /**
596
+ * Get the current cached credentials (may be expired)
597
+ *
598
+ * @returns The currently cached credentials or null
599
+ */
600
+ getCurrentCredentials(): QwenCredentials | null {
601
+ return this.memoryCache.credentials;
602
+ }
603
+
604
+ /**
605
+ * Check if there's an ongoing refresh operation
606
+ *
607
+ * @returns true if refresh is in progress, false otherwise
608
+ */
609
+ isRefreshInProgress(): boolean {
610
+ return this.refreshPromise !== null;
611
+ }
612
+
613
+ /**
614
+ * Set lock configuration for testing purposes
615
+ * @param config - Lock configuration
616
+ */
617
+ setLockConfig(config: Partial<LockConfig>): void {
618
+ this.lockConfig = { ...DEFAULT_LOCK_CONFIG, ...config };
619
+ }
620
+
621
+ /**
622
+ * Clean up event listeners (primarily for testing)
623
+ */
624
+ cleanup(): void {
625
+ if (this.cleanupFunction && this.cleanupHandlersRegistered) {
626
+ this.cleanupFunction();
627
+
628
+ process.removeListener('exit', this.cleanupFunction);
629
+ process.removeListener('SIGINT', this.cleanupFunction);
630
+ process.removeListener('SIGTERM', this.cleanupFunction);
631
+ process.removeListener('uncaughtException', this.cleanupFunction);
632
+ process.removeListener('unhandledRejection', this.cleanupFunction);
633
+
634
+ this.cleanupHandlersRegistered = false;
635
+ this.cleanupFunction = null;
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Get a summary of the current state for debugging
641
+ *
642
+ * @returns Object containing current state information
643
+ */
644
+ getDebugInfo(): {
645
+ hasCredentials: boolean;
646
+ credentialsExpired: boolean;
647
+ isRefreshing: boolean;
648
+ cacheAge: number;
649
+ } {
650
+ const hasCredentials = !!this.memoryCache.credentials;
651
+ const credentialsExpired = hasCredentials
652
+ ? !this.isTokenValid(this.memoryCache.credentials!)
653
+ : false;
654
+
655
+ return {
656
+ hasCredentials,
657
+ credentialsExpired,
658
+ isRefreshing: this.isRefreshInProgress(),
659
+ cacheAge: Date.now() - this.memoryCache.lastCheck,
660
+ };
661
+ }
662
+ }
projects/ui/qwen-code/packages/core/src/services/chatRecordingService.test.ts ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ expect,
9
+ it,
10
+ describe,
11
+ vi,
12
+ beforeEach,
13
+ afterEach,
14
+ MockInstance,
15
+ } from 'vitest';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { randomUUID } from 'node:crypto';
19
+ import {
20
+ ChatRecordingService,
21
+ ConversationRecord,
22
+ ToolCallRecord,
23
+ } from './chatRecordingService.js';
24
+ import { Config } from '../config/config.js';
25
+ import { getProjectHash } from '../utils/paths.js';
26
+
27
+ vi.mock('node:fs');
28
+ vi.mock('node:path');
29
+ vi.mock('node:crypto');
30
+ vi.mock('../utils/paths.js');
31
+
32
+ describe('ChatRecordingService', () => {
33
+ let chatRecordingService: ChatRecordingService;
34
+ let mockConfig: Config;
35
+
36
+ let mkdirSyncSpy: MockInstance<typeof fs.mkdirSync>;
37
+ let writeFileSyncSpy: MockInstance<typeof fs.writeFileSync>;
38
+
39
+ beforeEach(() => {
40
+ mockConfig = {
41
+ getSessionId: vi.fn().mockReturnValue('test-session-id'),
42
+ getProjectRoot: vi.fn().mockReturnValue('/test/project/root'),
43
+ getProjectTempDir: vi
44
+ .fn()
45
+ .mockReturnValue('/test/project/root/.gemini/tmp'),
46
+ getModel: vi.fn().mockReturnValue('gemini-pro'),
47
+ getDebugMode: vi.fn().mockReturnValue(false),
48
+ } as unknown as Config;
49
+
50
+ vi.mocked(getProjectHash).mockReturnValue('test-project-hash');
51
+ vi.mocked(randomUUID).mockReturnValue('this-is-a-test-uuid');
52
+ vi.mocked(path.join).mockImplementation((...args) => args.join('/'));
53
+
54
+ chatRecordingService = new ChatRecordingService(mockConfig);
55
+
56
+ mkdirSyncSpy = vi
57
+ .spyOn(fs, 'mkdirSync')
58
+ .mockImplementation(() => undefined);
59
+
60
+ writeFileSyncSpy = vi
61
+ .spyOn(fs, 'writeFileSync')
62
+ .mockImplementation(() => undefined);
63
+ });
64
+
65
+ afterEach(() => {
66
+ vi.restoreAllMocks();
67
+ });
68
+
69
+ describe('initialize', () => {
70
+ it('should create a new session if none is provided', () => {
71
+ chatRecordingService.initialize();
72
+
73
+ expect(mkdirSyncSpy).toHaveBeenCalledWith(
74
+ '/test/project/root/.gemini/tmp/chats',
75
+ { recursive: true },
76
+ );
77
+ expect(writeFileSyncSpy).not.toHaveBeenCalled();
78
+ });
79
+
80
+ it('should resume from an existing session if provided', () => {
81
+ const readFileSyncSpy = vi.spyOn(fs, 'readFileSync').mockReturnValue(
82
+ JSON.stringify({
83
+ sessionId: 'old-session-id',
84
+ projectHash: 'test-project-hash',
85
+ messages: [],
86
+ }),
87
+ );
88
+ const writeFileSyncSpy = vi
89
+ .spyOn(fs, 'writeFileSync')
90
+ .mockImplementation(() => undefined);
91
+
92
+ chatRecordingService.initialize({
93
+ filePath: '/test/project/root/.gemini/tmp/chats/session.json',
94
+ conversation: {
95
+ sessionId: 'old-session-id',
96
+ } as ConversationRecord,
97
+ });
98
+
99
+ expect(mkdirSyncSpy).not.toHaveBeenCalled();
100
+ expect(readFileSyncSpy).toHaveBeenCalled();
101
+ expect(writeFileSyncSpy).not.toHaveBeenCalled();
102
+ });
103
+ });
104
+
105
+ describe('recordMessage', () => {
106
+ beforeEach(() => {
107
+ chatRecordingService.initialize();
108
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(
109
+ JSON.stringify({
110
+ sessionId: 'test-session-id',
111
+ projectHash: 'test-project-hash',
112
+ messages: [],
113
+ }),
114
+ );
115
+ });
116
+
117
+ it('should record a new message', () => {
118
+ const writeFileSyncSpy = vi
119
+ .spyOn(fs, 'writeFileSync')
120
+ .mockImplementation(() => undefined);
121
+ chatRecordingService.recordMessage({ type: 'user', content: 'Hello' });
122
+ expect(mkdirSyncSpy).toHaveBeenCalled();
123
+ expect(writeFileSyncSpy).toHaveBeenCalled();
124
+ const conversation = JSON.parse(
125
+ writeFileSyncSpy.mock.calls[0][1] as string,
126
+ ) as ConversationRecord;
127
+ expect(conversation.messages).toHaveLength(1);
128
+ expect(conversation.messages[0].content).toBe('Hello');
129
+ expect(conversation.messages[0].type).toBe('user');
130
+ });
131
+
132
+ it('should append to the last message if append is true and types match', () => {
133
+ const writeFileSyncSpy = vi
134
+ .spyOn(fs, 'writeFileSync')
135
+ .mockImplementation(() => undefined);
136
+ const initialConversation = {
137
+ sessionId: 'test-session-id',
138
+ projectHash: 'test-project-hash',
139
+ messages: [
140
+ {
141
+ id: '1',
142
+ type: 'user',
143
+ content: 'Hello',
144
+ timestamp: new Date().toISOString(),
145
+ },
146
+ ],
147
+ };
148
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(
149
+ JSON.stringify(initialConversation),
150
+ );
151
+
152
+ chatRecordingService.recordMessage({
153
+ type: 'user',
154
+ content: ' World',
155
+ append: true,
156
+ });
157
+
158
+ expect(mkdirSyncSpy).toHaveBeenCalled();
159
+ expect(writeFileSyncSpy).toHaveBeenCalled();
160
+ const conversation = JSON.parse(
161
+ writeFileSyncSpy.mock.calls[0][1] as string,
162
+ ) as ConversationRecord;
163
+ expect(conversation.messages).toHaveLength(1);
164
+ expect(conversation.messages[0].content).toBe('Hello World');
165
+ });
166
+ });
167
+
168
+ describe('recordThought', () => {
169
+ it('should queue a thought', () => {
170
+ chatRecordingService.initialize();
171
+ chatRecordingService.recordThought({
172
+ subject: 'Thinking',
173
+ description: 'Thinking...',
174
+ });
175
+ // @ts-expect-error private property
176
+ expect(chatRecordingService.queuedThoughts).toHaveLength(1);
177
+ // @ts-expect-error private property
178
+ expect(chatRecordingService.queuedThoughts[0].subject).toBe('Thinking');
179
+ // @ts-expect-error private property
180
+ expect(chatRecordingService.queuedThoughts[0].description).toBe(
181
+ 'Thinking...',
182
+ );
183
+ });
184
+ });
185
+
186
+ describe('recordMessageTokens', () => {
187
+ beforeEach(() => {
188
+ chatRecordingService.initialize();
189
+ });
190
+
191
+ it('should update the last message with token info', () => {
192
+ const writeFileSyncSpy = vi
193
+ .spyOn(fs, 'writeFileSync')
194
+ .mockImplementation(() => undefined);
195
+ const initialConversation = {
196
+ sessionId: 'test-session-id',
197
+ projectHash: 'test-project-hash',
198
+ messages: [
199
+ {
200
+ id: '1',
201
+ type: 'gemini',
202
+ content: 'Response',
203
+ timestamp: new Date().toISOString(),
204
+ },
205
+ ],
206
+ };
207
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(
208
+ JSON.stringify(initialConversation),
209
+ );
210
+
211
+ chatRecordingService.recordMessageTokens({
212
+ input: 1,
213
+ output: 2,
214
+ total: 3,
215
+ cached: 0,
216
+ });
217
+
218
+ expect(mkdirSyncSpy).toHaveBeenCalled();
219
+ expect(writeFileSyncSpy).toHaveBeenCalled();
220
+ const conversation = JSON.parse(
221
+ writeFileSyncSpy.mock.calls[0][1] as string,
222
+ ) as ConversationRecord;
223
+ expect(conversation.messages[0]).toEqual({
224
+ ...initialConversation.messages[0],
225
+ tokens: { input: 1, output: 2, total: 3, cached: 0 },
226
+ });
227
+ });
228
+
229
+ it('should queue token info if the last message already has tokens', () => {
230
+ const initialConversation = {
231
+ sessionId: 'test-session-id',
232
+ projectHash: 'test-project-hash',
233
+ messages: [
234
+ {
235
+ id: '1',
236
+ type: 'gemini',
237
+ content: 'Response',
238
+ timestamp: new Date().toISOString(),
239
+ tokens: { input: 1, output: 1, total: 2, cached: 0 },
240
+ },
241
+ ],
242
+ };
243
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(
244
+ JSON.stringify(initialConversation),
245
+ );
246
+
247
+ chatRecordingService.recordMessageTokens({
248
+ input: 2,
249
+ output: 2,
250
+ total: 4,
251
+ cached: 0,
252
+ });
253
+
254
+ // @ts-expect-error private property
255
+ expect(chatRecordingService.queuedTokens).toEqual({
256
+ input: 2,
257
+ output: 2,
258
+ total: 4,
259
+ cached: 0,
260
+ });
261
+ });
262
+ });
263
+
264
+ describe('recordToolCalls', () => {
265
+ beforeEach(() => {
266
+ chatRecordingService.initialize();
267
+ });
268
+
269
+ it('should add new tool calls to the last message', () => {
270
+ const writeFileSyncSpy = vi
271
+ .spyOn(fs, 'writeFileSync')
272
+ .mockImplementation(() => undefined);
273
+ const initialConversation = {
274
+ sessionId: 'test-session-id',
275
+ projectHash: 'test-project-hash',
276
+ messages: [
277
+ {
278
+ id: '1',
279
+ type: 'gemini',
280
+ content: '',
281
+ timestamp: new Date().toISOString(),
282
+ },
283
+ ],
284
+ };
285
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(
286
+ JSON.stringify(initialConversation),
287
+ );
288
+
289
+ const toolCall: ToolCallRecord = {
290
+ id: 'tool-1',
291
+ name: 'testTool',
292
+ args: {},
293
+ status: 'awaiting_approval',
294
+ timestamp: new Date().toISOString(),
295
+ };
296
+ chatRecordingService.recordToolCalls([toolCall]);
297
+
298
+ expect(mkdirSyncSpy).toHaveBeenCalled();
299
+ expect(writeFileSyncSpy).toHaveBeenCalled();
300
+ const conversation = JSON.parse(
301
+ writeFileSyncSpy.mock.calls[0][1] as string,
302
+ ) as ConversationRecord;
303
+ expect(conversation.messages[0]).toEqual({
304
+ ...initialConversation.messages[0],
305
+ toolCalls: [toolCall],
306
+ });
307
+ });
308
+
309
+ it('should create a new message if the last message is not from gemini', () => {
310
+ const writeFileSyncSpy = vi
311
+ .spyOn(fs, 'writeFileSync')
312
+ .mockImplementation(() => undefined);
313
+ const initialConversation = {
314
+ sessionId: 'test-session-id',
315
+ projectHash: 'test-project-hash',
316
+ messages: [
317
+ {
318
+ id: 'a-uuid',
319
+ type: 'user',
320
+ content: 'call a tool',
321
+ timestamp: new Date().toISOString(),
322
+ },
323
+ ],
324
+ };
325
+ vi.spyOn(fs, 'readFileSync').mockReturnValue(
326
+ JSON.stringify(initialConversation),
327
+ );
328
+
329
+ const toolCall: ToolCallRecord = {
330
+ id: 'tool-1',
331
+ name: 'testTool',
332
+ args: {},
333
+ status: 'awaiting_approval',
334
+ timestamp: new Date().toISOString(),
335
+ };
336
+ chatRecordingService.recordToolCalls([toolCall]);
337
+
338
+ expect(mkdirSyncSpy).toHaveBeenCalled();
339
+ expect(writeFileSyncSpy).toHaveBeenCalled();
340
+ const conversation = JSON.parse(
341
+ writeFileSyncSpy.mock.calls[0][1] as string,
342
+ ) as ConversationRecord;
343
+ expect(conversation.messages).toHaveLength(2);
344
+ expect(conversation.messages[1]).toEqual({
345
+ ...conversation.messages[1],
346
+ id: 'this-is-a-test-uuid',
347
+ model: 'gemini-pro',
348
+ type: 'gemini',
349
+ thoughts: [],
350
+ content: '',
351
+ toolCalls: [toolCall],
352
+ });
353
+ });
354
+ });
355
+
356
+ describe('deleteSession', () => {
357
+ it('should delete the session file', () => {
358
+ const unlinkSyncSpy = vi
359
+ .spyOn(fs, 'unlinkSync')
360
+ .mockImplementation(() => undefined);
361
+ chatRecordingService.deleteSession('test-session-id');
362
+ expect(unlinkSyncSpy).toHaveBeenCalledWith(
363
+ '/test/project/root/.gemini/tmp/chats/test-session-id.json',
364
+ );
365
+ });
366
+ });
367
+ });
projects/ui/qwen-code/packages/core/src/services/chatRecordingService.ts ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { type Config } from '../config/config.js';
8
+ import { type Status } from '../core/coreToolScheduler.js';
9
+ import { type ThoughtSummary } from '../core/turn.js';
10
+ import { getProjectHash } from '../utils/paths.js';
11
+ import path from 'node:path';
12
+ import fs from 'node:fs';
13
+ import { randomUUID } from 'node:crypto';
14
+ import { PartListUnion } from '@google/genai';
15
+
16
+ /**
17
+ * Token usage summary for a message or conversation.
18
+ */
19
+ export interface TokensSummary {
20
+ input: number; // promptTokenCount
21
+ output: number; // candidatesTokenCount
22
+ cached: number; // cachedContentTokenCount
23
+ thoughts?: number; // thoughtsTokenCount
24
+ tool?: number; // toolUsePromptTokenCount
25
+ total: number; // totalTokenCount
26
+ }
27
+
28
+ /**
29
+ * Base fields common to all messages.
30
+ */
31
+ export interface BaseMessageRecord {
32
+ id: string;
33
+ timestamp: string;
34
+ content: string;
35
+ }
36
+
37
+ /**
38
+ * Record of a tool call execution within a conversation.
39
+ */
40
+ export interface ToolCallRecord {
41
+ id: string;
42
+ name: string;
43
+ args: Record<string, unknown>;
44
+ result?: PartListUnion | null;
45
+ status: Status;
46
+ timestamp: string;
47
+ // UI-specific fields for display purposes
48
+ displayName?: string;
49
+ description?: string;
50
+ resultDisplay?: string;
51
+ renderOutputAsMarkdown?: boolean;
52
+ }
53
+
54
+ /**
55
+ * Message type and message type-specific fields.
56
+ */
57
+ export type ConversationRecordExtra =
58
+ | {
59
+ type: 'user';
60
+ }
61
+ | {
62
+ type: 'gemini';
63
+ toolCalls?: ToolCallRecord[];
64
+ thoughts?: Array<ThoughtSummary & { timestamp: string }>;
65
+ tokens?: TokensSummary | null;
66
+ model?: string;
67
+ };
68
+
69
+ /**
70
+ * A single message record in a conversation.
71
+ */
72
+ export type MessageRecord = BaseMessageRecord & ConversationRecordExtra;
73
+
74
+ /**
75
+ * Complete conversation record stored in session files.
76
+ */
77
+ export interface ConversationRecord {
78
+ sessionId: string;
79
+ projectHash: string;
80
+ startTime: string;
81
+ lastUpdated: string;
82
+ messages: MessageRecord[];
83
+ }
84
+
85
+ /**
86
+ * Data structure for resuming an existing session.
87
+ */
88
+ export interface ResumedSessionData {
89
+ conversation: ConversationRecord;
90
+ filePath: string;
91
+ }
92
+
93
+ /**
94
+ * Service for automatically recording chat conversations to disk.
95
+ *
96
+ * This service provides comprehensive conversation recording that captures:
97
+ * - All user and assistant messages
98
+ * - Tool calls and their execution results
99
+ * - Token usage statistics
100
+ * - Assistant thoughts and reasoning
101
+ *
102
+ * Sessions are stored as JSON files in ~/.gemini/tmp/<project_hash>/chats/
103
+ */
104
+ export class ChatRecordingService {
105
+ private conversationFile: string | null = null;
106
+ private cachedLastConvData: string | null = null;
107
+ private sessionId: string;
108
+ private projectHash: string;
109
+ private queuedThoughts: Array<ThoughtSummary & { timestamp: string }> = [];
110
+ private queuedTokens: TokensSummary | null = null;
111
+ private config: Config;
112
+
113
+ constructor(config: Config) {
114
+ this.config = config;
115
+ this.sessionId = config.getSessionId();
116
+ this.projectHash = getProjectHash(config.getProjectRoot());
117
+ }
118
+
119
+ /**
120
+ * Initializes the chat recording service: creates a new conversation file and associates it with
121
+ * this service instance, or resumes from an existing session if resumedSessionData is provided.
122
+ */
123
+ initialize(resumedSessionData?: ResumedSessionData): void {
124
+ try {
125
+ if (resumedSessionData) {
126
+ // Resume from existing session
127
+ this.conversationFile = resumedSessionData.filePath;
128
+ this.sessionId = resumedSessionData.conversation.sessionId;
129
+
130
+ // Update the session ID in the existing file
131
+ this.updateConversation((conversation) => {
132
+ conversation.sessionId = this.sessionId;
133
+ });
134
+
135
+ // Clear any cached data to force fresh reads
136
+ this.cachedLastConvData = null;
137
+ } else {
138
+ // Create new session
139
+ const chatsDir = path.join(this.config.getProjectTempDir(), 'chats');
140
+ fs.mkdirSync(chatsDir, { recursive: true });
141
+
142
+ const timestamp = new Date()
143
+ .toISOString()
144
+ .slice(0, 16)
145
+ .replace(/:/g, '-');
146
+ const filename = `session-${timestamp}-${this.sessionId.slice(
147
+ 0,
148
+ 8,
149
+ )}.json`;
150
+ this.conversationFile = path.join(chatsDir, filename);
151
+
152
+ this.writeConversation({
153
+ sessionId: this.sessionId,
154
+ projectHash: this.projectHash,
155
+ startTime: new Date().toISOString(),
156
+ lastUpdated: new Date().toISOString(),
157
+ messages: [],
158
+ });
159
+ }
160
+
161
+ // Clear any queued data since this is a fresh start
162
+ this.queuedThoughts = [];
163
+ this.queuedTokens = null;
164
+ } catch (error) {
165
+ console.error('Error initializing chat recording service:', error);
166
+ throw error;
167
+ }
168
+ }
169
+
170
+ private getLastMessage(
171
+ conversation: ConversationRecord,
172
+ ): MessageRecord | undefined {
173
+ return conversation.messages.at(-1);
174
+ }
175
+
176
+ private newMessage(
177
+ type: ConversationRecordExtra['type'],
178
+ content: string,
179
+ ): MessageRecord {
180
+ return {
181
+ id: randomUUID(),
182
+ timestamp: new Date().toISOString(),
183
+ type,
184
+ content,
185
+ };
186
+ }
187
+
188
+ /**
189
+ * Records a message in the conversation.
190
+ */
191
+ recordMessage(message: {
192
+ type: ConversationRecordExtra['type'];
193
+ content: string;
194
+ append?: boolean;
195
+ }): void {
196
+ if (!this.conversationFile) return;
197
+
198
+ try {
199
+ this.updateConversation((conversation) => {
200
+ if (message.append) {
201
+ const lastMsg = this.getLastMessage(conversation);
202
+ if (lastMsg && lastMsg.type === message.type) {
203
+ lastMsg.content += message.content;
204
+ return;
205
+ }
206
+ }
207
+ // We're not appending, or we are appending but the last message's type is not the same as
208
+ // the specified type, so just create a new message.
209
+ const msg = this.newMessage(message.type, message.content);
210
+ if (msg.type === 'gemini') {
211
+ // If it's a new Gemini message then incorporate any queued thoughts.
212
+ conversation.messages.push({
213
+ ...msg,
214
+ thoughts: this.queuedThoughts,
215
+ tokens: this.queuedTokens,
216
+ model: this.config.getModel(),
217
+ });
218
+ this.queuedThoughts = [];
219
+ this.queuedTokens = null;
220
+ } else {
221
+ // Or else just add it.
222
+ conversation.messages.push(msg);
223
+ }
224
+ });
225
+ } catch (error) {
226
+ console.error('Error saving message:', error);
227
+ throw error;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Records a thought from the assistant's reasoning process.
233
+ */
234
+ recordThought(thought: ThoughtSummary): void {
235
+ if (!this.conversationFile) return;
236
+
237
+ try {
238
+ this.queuedThoughts.push({
239
+ ...thought,
240
+ timestamp: new Date().toISOString(),
241
+ });
242
+ } catch (error) {
243
+ if (this.config.getDebugMode()) {
244
+ console.error('Error saving thought:', error);
245
+ throw error;
246
+ }
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Updates the tokens for the last message in the conversation (which should be by Gemini).
252
+ */
253
+ recordMessageTokens(tokens: {
254
+ input: number;
255
+ output: number;
256
+ cached: number;
257
+ thoughts?: number;
258
+ tool?: number;
259
+ total: number;
260
+ }): void {
261
+ if (!this.conversationFile) return;
262
+
263
+ try {
264
+ this.updateConversation((conversation) => {
265
+ const lastMsg = this.getLastMessage(conversation);
266
+ // If the last message already has token info, it's because this new token info is for a
267
+ // new message that hasn't been recorded yet.
268
+ if (lastMsg && lastMsg.type === 'gemini' && !lastMsg.tokens) {
269
+ lastMsg.tokens = tokens;
270
+ this.queuedTokens = null;
271
+ } else {
272
+ this.queuedTokens = tokens;
273
+ }
274
+ });
275
+ } catch (error) {
276
+ console.error('Error updating message tokens:', error);
277
+ throw error;
278
+ }
279
+ }
280
+
281
+ /**
282
+ * Adds tool calls to the last message in the conversation (which should be by Gemini).
283
+ */
284
+ recordToolCalls(toolCalls: ToolCallRecord[]): void {
285
+ if (!this.conversationFile) return;
286
+
287
+ try {
288
+ this.updateConversation((conversation) => {
289
+ const lastMsg = this.getLastMessage(conversation);
290
+ // If a tool call was made, but the last message isn't from Gemini, it's because Gemini is
291
+ // calling tools without starting the message with text. So the user submits a prompt, and
292
+ // Gemini immediately calls a tool (maybe with some thinking first). In that case, create
293
+ // a new empty Gemini message.
294
+ // Also if there are any queued thoughts, it means this tool call(s) is from a new Gemini
295
+ // message--because it's thought some more since we last, if ever, created a new Gemini
296
+ // message from tool calls, when we dequeued the thoughts.
297
+ if (
298
+ !lastMsg ||
299
+ lastMsg.type !== 'gemini' ||
300
+ this.queuedThoughts.length > 0
301
+ ) {
302
+ const newMsg: MessageRecord = {
303
+ ...this.newMessage('gemini' as const, ''),
304
+ // This isn't strictly necessary, but TypeScript apparently can't
305
+ // tell that the first parameter to newMessage() becomes the
306
+ // resulting message's type, and so it thinks that toolCalls may
307
+ // not be present. Confirming the type here satisfies it.
308
+ type: 'gemini' as const,
309
+ toolCalls,
310
+ thoughts: this.queuedThoughts,
311
+ model: this.config.getModel(),
312
+ };
313
+ // If there are any queued thoughts join them to this message.
314
+ if (this.queuedThoughts.length > 0) {
315
+ newMsg.thoughts = this.queuedThoughts;
316
+ this.queuedThoughts = [];
317
+ }
318
+ // If there's any queued tokens info join it to this message.
319
+ if (this.queuedTokens) {
320
+ newMsg.tokens = this.queuedTokens;
321
+ this.queuedTokens = null;
322
+ }
323
+ conversation.messages.push(newMsg);
324
+ } else {
325
+ // The last message is an existing Gemini message that we need to update.
326
+
327
+ // Update any existing tool call entries.
328
+ if (!lastMsg.toolCalls) {
329
+ lastMsg.toolCalls = [];
330
+ }
331
+ lastMsg.toolCalls = lastMsg.toolCalls.map((toolCall) => {
332
+ // If there are multiple tool calls with the same ID, this will take the first one.
333
+ const incomingToolCall = toolCalls.find(
334
+ (tc) => tc.id === toolCall.id,
335
+ );
336
+ if (incomingToolCall) {
337
+ // Merge in the new data to keep preserve thoughts, etc., that were assigned to older
338
+ // versions of the tool call.
339
+ return { ...toolCall, ...incomingToolCall };
340
+ } else {
341
+ return toolCall;
342
+ }
343
+ });
344
+
345
+ // Add any new tools calls that aren't in the message yet.
346
+ for (const toolCall of toolCalls) {
347
+ const existingToolCall = lastMsg.toolCalls.find(
348
+ (tc) => tc.id === toolCall.id,
349
+ );
350
+ if (!existingToolCall) {
351
+ lastMsg.toolCalls.push(toolCall);
352
+ }
353
+ }
354
+ }
355
+ });
356
+ } catch (error) {
357
+ console.error('Error adding tool call to message:', error);
358
+ throw error;
359
+ }
360
+ }
361
+
362
+ /**
363
+ * Loads up the conversation record from disk.
364
+ */
365
+ private readConversation(): ConversationRecord {
366
+ try {
367
+ this.cachedLastConvData = fs.readFileSync(this.conversationFile!, 'utf8');
368
+ return JSON.parse(this.cachedLastConvData);
369
+ } catch (error) {
370
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
371
+ console.error('Error reading conversation file:', error);
372
+ throw error;
373
+ }
374
+
375
+ // Placeholder empty conversation if file doesn't exist.
376
+ return {
377
+ sessionId: this.sessionId,
378
+ projectHash: this.projectHash,
379
+ startTime: new Date().toISOString(),
380
+ lastUpdated: new Date().toISOString(),
381
+ messages: [],
382
+ };
383
+ }
384
+ }
385
+
386
+ /**
387
+ * Saves the conversation record; overwrites the file.
388
+ */
389
+ private writeConversation(conversation: ConversationRecord): void {
390
+ try {
391
+ if (!this.conversationFile) return;
392
+ // Don't write the file yet until there's at least one message.
393
+ if (conversation.messages.length === 0) return;
394
+
395
+ // Only write the file if this change would change the file.
396
+ if (this.cachedLastConvData !== JSON.stringify(conversation, null, 2)) {
397
+ conversation.lastUpdated = new Date().toISOString();
398
+ const newContent = JSON.stringify(conversation, null, 2);
399
+ this.cachedLastConvData = newContent;
400
+ fs.writeFileSync(this.conversationFile, newContent);
401
+ }
402
+ } catch (error) {
403
+ console.error('Error writing conversation file:', error);
404
+ throw error;
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Convenient helper for updating the conversation without file reading and writing and time
410
+ * updating boilerplate.
411
+ */
412
+ private updateConversation(
413
+ updateFn: (conversation: ConversationRecord) => void,
414
+ ) {
415
+ const conversation = this.readConversation();
416
+ updateFn(conversation);
417
+ this.writeConversation(conversation);
418
+ }
419
+
420
+ /**
421
+ * Deletes a session file by session ID.
422
+ */
423
+ deleteSession(sessionId: string): void {
424
+ try {
425
+ const chatsDir = path.join(this.config.getProjectTempDir(), 'chats');
426
+ const sessionPath = path.join(chatsDir, `${sessionId}.json`);
427
+ fs.unlinkSync(sessionPath);
428
+ } catch (error) {
429
+ console.error('Error deleting session:', error);
430
+ throw error;
431
+ }
432
+ }
433
+ }
projects/ui/qwen-code/packages/core/src/services/fileDiscoveryService.test.ts ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import * as fs from 'fs/promises';
9
+ import * as os from 'os';
10
+ import * as path from 'path';
11
+ import { FileDiscoveryService } from './fileDiscoveryService.js';
12
+
13
+ describe('FileDiscoveryService', () => {
14
+ let testRootDir: string;
15
+ let projectRoot: string;
16
+
17
+ async function createTestFile(filePath: string, content = '') {
18
+ const fullPath = path.join(projectRoot, filePath);
19
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
20
+ await fs.writeFile(fullPath, content);
21
+ return fullPath;
22
+ }
23
+
24
+ beforeEach(async () => {
25
+ testRootDir = await fs.mkdtemp(
26
+ path.join(os.tmpdir(), 'file-discovery-test-'),
27
+ );
28
+ projectRoot = path.join(testRootDir, 'project');
29
+ await fs.mkdir(projectRoot, { recursive: true });
30
+ });
31
+
32
+ afterEach(async () => {
33
+ await fs.rm(testRootDir, { recursive: true, force: true });
34
+ });
35
+
36
+ describe('initialization', () => {
37
+ it('should initialize git ignore parser by default in a git repo', async () => {
38
+ await fs.mkdir(path.join(projectRoot, '.git'));
39
+ await createTestFile('.gitignore', 'node_modules/');
40
+
41
+ const service = new FileDiscoveryService(projectRoot);
42
+ // Let's check the effect of the parser instead of mocking it.
43
+ expect(service.shouldGitIgnoreFile('node_modules/foo.js')).toBe(true);
44
+ expect(service.shouldGitIgnoreFile('src/foo.js')).toBe(false);
45
+ });
46
+
47
+ it('should not load git repo patterns when not in a git repo', async () => {
48
+ // No .git directory
49
+ await createTestFile('.gitignore', 'node_modules/');
50
+ const service = new FileDiscoveryService(projectRoot);
51
+
52
+ // .gitignore is not loaded in non-git repos
53
+ expect(service.shouldGitIgnoreFile('node_modules/foo.js')).toBe(false);
54
+ });
55
+
56
+ it('should load .geminiignore patterns even when not in a git repo', async () => {
57
+ await createTestFile('.geminiignore', 'secrets.txt');
58
+ const service = new FileDiscoveryService(projectRoot);
59
+
60
+ expect(service.shouldGeminiIgnoreFile('secrets.txt')).toBe(true);
61
+ expect(service.shouldGeminiIgnoreFile('src/index.js')).toBe(false);
62
+ });
63
+ });
64
+
65
+ describe('filterFiles', () => {
66
+ beforeEach(async () => {
67
+ await fs.mkdir(path.join(projectRoot, '.git'));
68
+ await createTestFile('.gitignore', 'node_modules/\n.git/\ndist');
69
+ await createTestFile('.geminiignore', 'logs/');
70
+ });
71
+
72
+ it('should filter out git-ignored and gemini-ignored files by default', () => {
73
+ const files = [
74
+ 'src/index.ts',
75
+ 'node_modules/package/index.js',
76
+ 'README.md',
77
+ '.git/config',
78
+ 'dist/bundle.js',
79
+ 'logs/latest.log',
80
+ ].map((f) => path.join(projectRoot, f));
81
+
82
+ const service = new FileDiscoveryService(projectRoot);
83
+
84
+ expect(service.filterFiles(files)).toEqual(
85
+ ['src/index.ts', 'README.md'].map((f) => path.join(projectRoot, f)),
86
+ );
87
+ });
88
+
89
+ it('should not filter files when respectGitIgnore is false', () => {
90
+ const files = [
91
+ 'src/index.ts',
92
+ 'node_modules/package/index.js',
93
+ '.git/config',
94
+ 'logs/latest.log',
95
+ ].map((f) => path.join(projectRoot, f));
96
+
97
+ const service = new FileDiscoveryService(projectRoot);
98
+
99
+ const filtered = service.filterFiles(files, {
100
+ respectGitIgnore: false,
101
+ respectGeminiIgnore: true, // still respect this one
102
+ });
103
+
104
+ expect(filtered).toEqual(
105
+ ['src/index.ts', 'node_modules/package/index.js', '.git/config'].map(
106
+ (f) => path.join(projectRoot, f),
107
+ ),
108
+ );
109
+ });
110
+
111
+ it('should not filter files when respectGeminiIgnore is false', () => {
112
+ const files = [
113
+ 'src/index.ts',
114
+ 'node_modules/package/index.js',
115
+ 'logs/latest.log',
116
+ ].map((f) => path.join(projectRoot, f));
117
+
118
+ const service = new FileDiscoveryService(projectRoot);
119
+
120
+ const filtered = service.filterFiles(files, {
121
+ respectGitIgnore: true,
122
+ respectGeminiIgnore: false,
123
+ });
124
+
125
+ expect(filtered).toEqual(
126
+ ['src/index.ts', 'logs/latest.log'].map((f) =>
127
+ path.join(projectRoot, f),
128
+ ),
129
+ );
130
+ });
131
+
132
+ it('should handle empty file list', () => {
133
+ const service = new FileDiscoveryService(projectRoot);
134
+
135
+ expect(service.filterFiles([])).toEqual([]);
136
+ });
137
+ });
138
+
139
+ describe('shouldGitIgnoreFile & shouldGeminiIgnoreFile', () => {
140
+ beforeEach(async () => {
141
+ await fs.mkdir(path.join(projectRoot, '.git'));
142
+ await createTestFile('.gitignore', 'node_modules/');
143
+ await createTestFile('.geminiignore', '*.log');
144
+ });
145
+
146
+ it('should return true for git-ignored files', () => {
147
+ const service = new FileDiscoveryService(projectRoot);
148
+
149
+ expect(
150
+ service.shouldGitIgnoreFile(
151
+ path.join(projectRoot, 'node_modules/package/index.js'),
152
+ ),
153
+ ).toBe(true);
154
+ });
155
+
156
+ it('should return false for non-git-ignored files', () => {
157
+ const service = new FileDiscoveryService(projectRoot);
158
+
159
+ expect(
160
+ service.shouldGitIgnoreFile(path.join(projectRoot, 'src/index.ts')),
161
+ ).toBe(false);
162
+ });
163
+
164
+ it('should return true for gemini-ignored files', () => {
165
+ const service = new FileDiscoveryService(projectRoot);
166
+
167
+ expect(
168
+ service.shouldGeminiIgnoreFile(path.join(projectRoot, 'debug.log')),
169
+ ).toBe(true);
170
+ });
171
+
172
+ it('should return false for non-gemini-ignored files', () => {
173
+ const service = new FileDiscoveryService(projectRoot);
174
+
175
+ expect(
176
+ service.shouldGeminiIgnoreFile(path.join(projectRoot, 'src/index.ts')),
177
+ ).toBe(false);
178
+ });
179
+ });
180
+
181
+ describe('edge cases', () => {
182
+ it('should handle relative project root paths', async () => {
183
+ await fs.mkdir(path.join(projectRoot, '.git'));
184
+ await createTestFile('.gitignore', 'ignored.txt');
185
+ const service = new FileDiscoveryService(
186
+ path.relative(process.cwd(), projectRoot),
187
+ );
188
+
189
+ expect(
190
+ service.shouldGitIgnoreFile(path.join(projectRoot, 'ignored.txt')),
191
+ ).toBe(true);
192
+ expect(
193
+ service.shouldGitIgnoreFile(path.join(projectRoot, 'not-ignored.txt')),
194
+ ).toBe(false);
195
+ });
196
+
197
+ it('should handle filterFiles with undefined options', async () => {
198
+ await fs.mkdir(path.join(projectRoot, '.git'));
199
+ await createTestFile('.gitignore', 'ignored.txt');
200
+ const service = new FileDiscoveryService(projectRoot);
201
+
202
+ const files = ['src/index.ts', 'ignored.txt'].map((f) =>
203
+ path.join(projectRoot, f),
204
+ );
205
+
206
+ expect(service.filterFiles(files, undefined)).toEqual([
207
+ path.join(projectRoot, 'src/index.ts'),
208
+ ]);
209
+ });
210
+ });
211
+ });
projects/ui/qwen-code/packages/core/src/services/fileDiscoveryService.ts ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { GitIgnoreParser, GitIgnoreFilter } from '../utils/gitIgnoreParser.js';
8
+ import { isGitRepository } from '../utils/gitUtils.js';
9
+ import * as path from 'path';
10
+
11
+ const GEMINI_IGNORE_FILE_NAME = '.geminiignore';
12
+
13
+ export interface FilterFilesOptions {
14
+ respectGitIgnore?: boolean;
15
+ respectGeminiIgnore?: boolean;
16
+ }
17
+
18
+ export class FileDiscoveryService {
19
+ private gitIgnoreFilter: GitIgnoreFilter | null = null;
20
+ private geminiIgnoreFilter: GitIgnoreFilter | null = null;
21
+ private projectRoot: string;
22
+
23
+ constructor(projectRoot: string) {
24
+ this.projectRoot = path.resolve(projectRoot);
25
+ if (isGitRepository(this.projectRoot)) {
26
+ const parser = new GitIgnoreParser(this.projectRoot);
27
+ try {
28
+ parser.loadGitRepoPatterns();
29
+ } catch (_error) {
30
+ // ignore file not found
31
+ }
32
+ this.gitIgnoreFilter = parser;
33
+ }
34
+ const gParser = new GitIgnoreParser(this.projectRoot);
35
+ try {
36
+ gParser.loadPatterns(GEMINI_IGNORE_FILE_NAME);
37
+ } catch (_error) {
38
+ // ignore file not found
39
+ }
40
+ this.geminiIgnoreFilter = gParser;
41
+ }
42
+
43
+ /**
44
+ * Filters a list of file paths based on git ignore rules
45
+ */
46
+ filterFiles(
47
+ filePaths: string[],
48
+ options: FilterFilesOptions = {
49
+ respectGitIgnore: true,
50
+ respectGeminiIgnore: true,
51
+ },
52
+ ): string[] {
53
+ return filePaths.filter((filePath) => {
54
+ if (options.respectGitIgnore && this.shouldGitIgnoreFile(filePath)) {
55
+ return false;
56
+ }
57
+ if (
58
+ options.respectGeminiIgnore &&
59
+ this.shouldGeminiIgnoreFile(filePath)
60
+ ) {
61
+ return false;
62
+ }
63
+ return true;
64
+ });
65
+ }
66
+
67
+ /**
68
+ * Checks if a single file should be git-ignored
69
+ */
70
+ shouldGitIgnoreFile(filePath: string): boolean {
71
+ if (this.gitIgnoreFilter) {
72
+ return this.gitIgnoreFilter.isIgnored(filePath);
73
+ }
74
+ return false;
75
+ }
76
+
77
+ /**
78
+ * Checks if a single file should be gemini-ignored
79
+ */
80
+ shouldGeminiIgnoreFile(filePath: string): boolean {
81
+ if (this.geminiIgnoreFilter) {
82
+ return this.geminiIgnoreFilter.isIgnored(filePath);
83
+ }
84
+ return false;
85
+ }
86
+
87
+ /**
88
+ * Unified method to check if a file should be ignored based on filtering options
89
+ */
90
+ shouldIgnoreFile(
91
+ filePath: string,
92
+ options: FilterFilesOptions = {},
93
+ ): boolean {
94
+ const { respectGitIgnore = true, respectGeminiIgnore = true } = options;
95
+
96
+ if (respectGitIgnore && this.shouldGitIgnoreFile(filePath)) {
97
+ return true;
98
+ }
99
+ if (respectGeminiIgnore && this.shouldGeminiIgnoreFile(filePath)) {
100
+ return true;
101
+ }
102
+ return false;
103
+ }
104
+
105
+ /**
106
+ * Returns loaded patterns from .geminiignore
107
+ */
108
+ getGeminiIgnorePatterns(): string[] {
109
+ return this.geminiIgnoreFilter?.getPatterns() ?? [];
110
+ }
111
+ }
projects/ui/qwen-code/packages/core/src/services/fileSystemService.test.ts ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 fs from 'fs/promises';
9
+ import { StandardFileSystemService } from './fileSystemService.js';
10
+
11
+ vi.mock('fs/promises');
12
+
13
+ describe('StandardFileSystemService', () => {
14
+ let fileSystem: StandardFileSystemService;
15
+
16
+ beforeEach(() => {
17
+ vi.resetAllMocks();
18
+ fileSystem = new StandardFileSystemService();
19
+ });
20
+
21
+ afterEach(() => {
22
+ vi.restoreAllMocks();
23
+ });
24
+
25
+ describe('readTextFile', () => {
26
+ it('should read file content using fs', async () => {
27
+ const testContent = 'Hello, World!';
28
+ vi.mocked(fs.readFile).mockResolvedValue(testContent);
29
+
30
+ const result = await fileSystem.readTextFile('/test/file.txt');
31
+
32
+ expect(fs.readFile).toHaveBeenCalledWith('/test/file.txt', 'utf-8');
33
+ expect(result).toBe(testContent);
34
+ });
35
+
36
+ it('should propagate fs.readFile errors', async () => {
37
+ const error = new Error('ENOENT: File not found');
38
+ vi.mocked(fs.readFile).mockRejectedValue(error);
39
+
40
+ await expect(fileSystem.readTextFile('/test/file.txt')).rejects.toThrow(
41
+ 'ENOENT: File not found',
42
+ );
43
+ });
44
+ });
45
+
46
+ describe('writeTextFile', () => {
47
+ it('should write file content using fs', async () => {
48
+ vi.mocked(fs.writeFile).mockResolvedValue();
49
+
50
+ await fileSystem.writeTextFile('/test/file.txt', 'Hello, World!');
51
+
52
+ expect(fs.writeFile).toHaveBeenCalledWith(
53
+ '/test/file.txt',
54
+ 'Hello, World!',
55
+ 'utf-8',
56
+ );
57
+ });
58
+ });
59
+ });
projects/ui/qwen-code/packages/core/src/services/fileSystemService.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import fs from 'fs/promises';
8
+
9
+ /**
10
+ * Interface for file system operations that may be delegated to different implementations
11
+ */
12
+ export interface FileSystemService {
13
+ /**
14
+ * Read text content from a file
15
+ *
16
+ * @param filePath - The path to the file to read
17
+ * @returns The file content as a string
18
+ */
19
+ readTextFile(filePath: string): Promise<string>;
20
+
21
+ /**
22
+ * Write text content to a file
23
+ *
24
+ * @param filePath - The path to the file to write
25
+ * @param content - The content to write
26
+ */
27
+ writeTextFile(filePath: string, content: string): Promise<void>;
28
+ }
29
+
30
+ /**
31
+ * Standard file system implementation
32
+ */
33
+ export class StandardFileSystemService implements FileSystemService {
34
+ async readTextFile(filePath: string): Promise<string> {
35
+ return fs.readFile(filePath, 'utf-8');
36
+ }
37
+
38
+ async writeTextFile(filePath: string, content: string): Promise<void> {
39
+ await fs.writeFile(filePath, content, 'utf-8');
40
+ }
41
+ }
projects/ui/qwen-code/packages/core/src/services/gitService.test.ts ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { GitService } from './gitService.js';
9
+ import * as path from 'path';
10
+ import * as fs from 'fs/promises';
11
+ import * as os from 'os';
12
+ import type { ChildProcess } from 'node:child_process';
13
+ import { getProjectHash, QWEN_DIR } from '../utils/paths.js';
14
+
15
+ const hoistedMockExec = vi.hoisted(() => vi.fn());
16
+ vi.mock('node:child_process', () => ({
17
+ exec: hoistedMockExec,
18
+ }));
19
+
20
+ const hoistedMockEnv = vi.hoisted(() => vi.fn());
21
+ const hoistedMockSimpleGit = vi.hoisted(() => vi.fn());
22
+ const hoistedMockCheckIsRepo = vi.hoisted(() => vi.fn());
23
+ const hoistedMockInit = vi.hoisted(() => vi.fn());
24
+ const hoistedMockRaw = vi.hoisted(() => vi.fn());
25
+ const hoistedMockAdd = vi.hoisted(() => vi.fn());
26
+ const hoistedMockCommit = vi.hoisted(() => vi.fn());
27
+ vi.mock('simple-git', () => ({
28
+ simpleGit: hoistedMockSimpleGit.mockImplementation(() => ({
29
+ checkIsRepo: hoistedMockCheckIsRepo,
30
+ init: hoistedMockInit,
31
+ raw: hoistedMockRaw,
32
+ add: hoistedMockAdd,
33
+ commit: hoistedMockCommit,
34
+ env: hoistedMockEnv,
35
+ })),
36
+ CheckRepoActions: { IS_REPO_ROOT: 'is-repo-root' },
37
+ }));
38
+
39
+ const hoistedIsGitRepositoryMock = vi.hoisted(() => vi.fn());
40
+ vi.mock('../utils/gitUtils.js', () => ({
41
+ isGitRepository: hoistedIsGitRepositoryMock,
42
+ }));
43
+
44
+ const hoistedMockHomedir = vi.hoisted(() => vi.fn());
45
+ vi.mock('os', async (importOriginal) => {
46
+ const actual = await importOriginal<typeof os>();
47
+ return {
48
+ ...actual,
49
+ homedir: hoistedMockHomedir,
50
+ };
51
+ });
52
+
53
+ describe('GitService', () => {
54
+ let testRootDir: string;
55
+ let projectRoot: string;
56
+ let homedir: string;
57
+ let hash: string;
58
+
59
+ beforeEach(async () => {
60
+ testRootDir = await fs.mkdtemp(path.join(os.tmpdir(), 'git-service-test-'));
61
+ projectRoot = path.join(testRootDir, 'project');
62
+ homedir = path.join(testRootDir, 'home');
63
+ await fs.mkdir(projectRoot, { recursive: true });
64
+ await fs.mkdir(homedir, { recursive: true });
65
+
66
+ hash = getProjectHash(projectRoot);
67
+
68
+ vi.clearAllMocks();
69
+ hoistedIsGitRepositoryMock.mockReturnValue(true);
70
+ hoistedMockExec.mockImplementation((command, callback) => {
71
+ if (command === 'git --version') {
72
+ callback(null, 'git version 2.0.0');
73
+ } else {
74
+ callback(new Error('Command not mocked'));
75
+ }
76
+ return {};
77
+ });
78
+
79
+ hoistedMockHomedir.mockReturnValue(homedir);
80
+
81
+ hoistedMockEnv.mockImplementation(() => ({
82
+ checkIsRepo: hoistedMockCheckIsRepo,
83
+ init: hoistedMockInit,
84
+ raw: hoistedMockRaw,
85
+ add: hoistedMockAdd,
86
+ commit: hoistedMockCommit,
87
+ }));
88
+ hoistedMockSimpleGit.mockImplementation(() => ({
89
+ checkIsRepo: hoistedMockCheckIsRepo,
90
+ init: hoistedMockInit,
91
+ raw: hoistedMockRaw,
92
+ add: hoistedMockAdd,
93
+ commit: hoistedMockCommit,
94
+ env: hoistedMockEnv,
95
+ }));
96
+ hoistedMockCheckIsRepo.mockResolvedValue(false);
97
+ hoistedMockInit.mockResolvedValue(undefined);
98
+ hoistedMockRaw.mockResolvedValue('');
99
+ hoistedMockAdd.mockResolvedValue(undefined);
100
+ hoistedMockCommit.mockResolvedValue({
101
+ commit: 'initial',
102
+ });
103
+ });
104
+
105
+ afterEach(async () => {
106
+ vi.restoreAllMocks();
107
+ await fs.rm(testRootDir, { recursive: true, force: true });
108
+ });
109
+
110
+ describe('constructor', () => {
111
+ it('should successfully create an instance', () => {
112
+ expect(() => new GitService(projectRoot)).not.toThrow();
113
+ });
114
+ });
115
+
116
+ describe('verifyGitAvailability', () => {
117
+ it('should resolve true if git --version command succeeds', async () => {
118
+ const service = new GitService(projectRoot);
119
+ await expect(service.verifyGitAvailability()).resolves.toBe(true);
120
+ });
121
+
122
+ it('should resolve false if git --version command fails', async () => {
123
+ hoistedMockExec.mockImplementation((command, callback) => {
124
+ callback(new Error('git not found'));
125
+ return {} as ChildProcess;
126
+ });
127
+ const service = new GitService(projectRoot);
128
+ await expect(service.verifyGitAvailability()).resolves.toBe(false);
129
+ });
130
+ });
131
+
132
+ describe('initialize', () => {
133
+ it('should throw an error if Git is not available', async () => {
134
+ hoistedMockExec.mockImplementation((command, callback) => {
135
+ callback(new Error('git not found'));
136
+ return {} as ChildProcess;
137
+ });
138
+ const service = new GitService(projectRoot);
139
+ await expect(service.initialize()).rejects.toThrow(
140
+ 'Checkpointing is enabled, but Git is not installed. Please install Git or disable checkpointing to continue.',
141
+ );
142
+ });
143
+
144
+ it('should call setupShadowGitRepository if Git is available', async () => {
145
+ const service = new GitService(projectRoot);
146
+ const setupSpy = vi
147
+ .spyOn(service, 'setupShadowGitRepository')
148
+ .mockResolvedValue(undefined);
149
+
150
+ await service.initialize();
151
+ expect(setupSpy).toHaveBeenCalled();
152
+ });
153
+ });
154
+
155
+ describe('setupShadowGitRepository', () => {
156
+ let repoDir: string;
157
+ let gitConfigPath: string;
158
+
159
+ beforeEach(() => {
160
+ repoDir = path.join(homedir, QWEN_DIR, 'history', hash);
161
+ gitConfigPath = path.join(repoDir, '.gitconfig');
162
+ });
163
+
164
+ it('should create history and repository directories', async () => {
165
+ const service = new GitService(projectRoot);
166
+ await service.setupShadowGitRepository();
167
+ const stats = await fs.stat(repoDir);
168
+ expect(stats.isDirectory()).toBe(true);
169
+ });
170
+
171
+ it('should create a .gitconfig file with the correct content', async () => {
172
+ const service = new GitService(projectRoot);
173
+ await service.setupShadowGitRepository();
174
+
175
+ const expectedConfigContent =
176
+ '[user]\n name = Gemini CLI\n email = gemini-cli@google.com\n[commit]\n gpgsign = false\n';
177
+ const actualConfigContent = await fs.readFile(gitConfigPath, 'utf-8');
178
+ expect(actualConfigContent).toBe(expectedConfigContent);
179
+ });
180
+
181
+ it('should initialize git repo in historyDir if not already initialized', async () => {
182
+ hoistedMockCheckIsRepo.mockResolvedValue(false);
183
+ const service = new GitService(projectRoot);
184
+ await service.setupShadowGitRepository();
185
+ expect(hoistedMockSimpleGit).toHaveBeenCalledWith(repoDir);
186
+ expect(hoistedMockInit).toHaveBeenCalled();
187
+ });
188
+
189
+ it('should not initialize git repo if already initialized', async () => {
190
+ hoistedMockCheckIsRepo.mockResolvedValue(true);
191
+ const service = new GitService(projectRoot);
192
+ await service.setupShadowGitRepository();
193
+ expect(hoistedMockInit).not.toHaveBeenCalled();
194
+ });
195
+
196
+ it('should copy .gitignore from projectRoot if it exists', async () => {
197
+ const gitignoreContent = 'node_modules/\n.env';
198
+ const visibleGitIgnorePath = path.join(projectRoot, '.gitignore');
199
+ await fs.writeFile(visibleGitIgnorePath, gitignoreContent);
200
+
201
+ const service = new GitService(projectRoot);
202
+ await service.setupShadowGitRepository();
203
+
204
+ const hiddenGitIgnorePath = path.join(repoDir, '.gitignore');
205
+ const copiedContent = await fs.readFile(hiddenGitIgnorePath, 'utf-8');
206
+ expect(copiedContent).toBe(gitignoreContent);
207
+ });
208
+
209
+ it('should not create a .gitignore in shadow repo if project .gitignore does not exist', async () => {
210
+ const service = new GitService(projectRoot);
211
+ await service.setupShadowGitRepository();
212
+
213
+ const hiddenGitIgnorePath = path.join(repoDir, '.gitignore');
214
+ // An empty string is written if the file doesn't exist.
215
+ const content = await fs.readFile(hiddenGitIgnorePath, 'utf-8');
216
+ expect(content).toBe('');
217
+ });
218
+
219
+ it('should throw an error if reading projectRoot .gitignore fails with other errors', async () => {
220
+ const visibleGitIgnorePath = path.join(projectRoot, '.gitignore');
221
+ // Create a directory instead of a file to cause a read error
222
+ await fs.mkdir(visibleGitIgnorePath);
223
+
224
+ const service = new GitService(projectRoot);
225
+ // EISDIR is the expected error code on Unix-like systems
226
+ await expect(service.setupShadowGitRepository()).rejects.toThrow(
227
+ /EISDIR: illegal operation on a directory, read|EBUSY: resource busy or locked, read/,
228
+ );
229
+ });
230
+
231
+ it('should make an initial commit if no commits exist in history repo', async () => {
232
+ hoistedMockCheckIsRepo.mockResolvedValue(false);
233
+ const service = new GitService(projectRoot);
234
+ await service.setupShadowGitRepository();
235
+ expect(hoistedMockCommit).toHaveBeenCalledWith('Initial commit', {
236
+ '--allow-empty': null,
237
+ });
238
+ });
239
+
240
+ it('should not make an initial commit if commits already exist', async () => {
241
+ hoistedMockCheckIsRepo.mockResolvedValue(true);
242
+ const service = new GitService(projectRoot);
243
+ await service.setupShadowGitRepository();
244
+ expect(hoistedMockCommit).not.toHaveBeenCalled();
245
+ });
246
+ });
247
+ });
projects/ui/qwen-code/packages/core/src/services/gitService.ts ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'fs/promises';
8
+ import * as path from 'path';
9
+ import * as os from 'os';
10
+ import { isNodeError } from '../utils/errors.js';
11
+ import { exec } from 'node:child_process';
12
+ import { simpleGit, SimpleGit, CheckRepoActions } from 'simple-git';
13
+ import { getProjectHash, QWEN_DIR } from '../utils/paths.js';
14
+
15
+ export class GitService {
16
+ private projectRoot: string;
17
+
18
+ constructor(projectRoot: string) {
19
+ this.projectRoot = path.resolve(projectRoot);
20
+ }
21
+
22
+ private getHistoryDir(): string {
23
+ const hash = getProjectHash(this.projectRoot);
24
+ return path.join(os.homedir(), QWEN_DIR, 'history', hash);
25
+ }
26
+
27
+ async initialize(): Promise<void> {
28
+ const gitAvailable = await this.verifyGitAvailability();
29
+ if (!gitAvailable) {
30
+ throw new Error(
31
+ 'Checkpointing is enabled, but Git is not installed. Please install Git or disable checkpointing to continue.',
32
+ );
33
+ }
34
+ this.setupShadowGitRepository();
35
+ }
36
+
37
+ verifyGitAvailability(): Promise<boolean> {
38
+ return new Promise((resolve) => {
39
+ exec('git --version', (error) => {
40
+ if (error) {
41
+ resolve(false);
42
+ } else {
43
+ resolve(true);
44
+ }
45
+ });
46
+ });
47
+ }
48
+
49
+ /**
50
+ * Creates a hidden git repository in the project root.
51
+ * The Git repository is used to support checkpointing.
52
+ */
53
+ async setupShadowGitRepository() {
54
+ const repoDir = this.getHistoryDir();
55
+ const gitConfigPath = path.join(repoDir, '.gitconfig');
56
+
57
+ await fs.mkdir(repoDir, { recursive: true });
58
+
59
+ // We don't want to inherit the user's name, email, or gpg signing
60
+ // preferences for the shadow repository, so we create a dedicated gitconfig.
61
+ const gitConfigContent =
62
+ '[user]\n name = Gemini CLI\n email = gemini-cli@google.com\n[commit]\n gpgsign = false\n';
63
+ await fs.writeFile(gitConfigPath, gitConfigContent);
64
+
65
+ const repo = simpleGit(repoDir);
66
+ const isRepoDefined = await repo.checkIsRepo(CheckRepoActions.IS_REPO_ROOT);
67
+
68
+ if (!isRepoDefined) {
69
+ await repo.init(false, {
70
+ '--initial-branch': 'main',
71
+ });
72
+
73
+ await repo.commit('Initial commit', { '--allow-empty': null });
74
+ }
75
+
76
+ const userGitIgnorePath = path.join(this.projectRoot, '.gitignore');
77
+ const shadowGitIgnorePath = path.join(repoDir, '.gitignore');
78
+
79
+ let userGitIgnoreContent = '';
80
+ try {
81
+ userGitIgnoreContent = await fs.readFile(userGitIgnorePath, 'utf-8');
82
+ } catch (error) {
83
+ if (isNodeError(error) && error.code !== 'ENOENT') {
84
+ throw error;
85
+ }
86
+ }
87
+
88
+ await fs.writeFile(shadowGitIgnorePath, userGitIgnoreContent);
89
+ }
90
+
91
+ private get shadowGitRepository(): SimpleGit {
92
+ const repoDir = this.getHistoryDir();
93
+ return simpleGit(this.projectRoot).env({
94
+ GIT_DIR: path.join(repoDir, '.git'),
95
+ GIT_WORK_TREE: this.projectRoot,
96
+ // Prevent git from using the user's global git config.
97
+ HOME: repoDir,
98
+ XDG_CONFIG_HOME: repoDir,
99
+ });
100
+ }
101
+
102
+ async getCurrentCommitHash(): Promise<string> {
103
+ const hash = await this.shadowGitRepository.raw('rev-parse', 'HEAD');
104
+ return hash.trim();
105
+ }
106
+
107
+ async createFileSnapshot(message: string): Promise<string> {
108
+ const repo = this.shadowGitRepository;
109
+ await repo.add('.');
110
+ const commitResult = await repo.commit(message);
111
+ return commitResult.commit;
112
+ }
113
+
114
+ async restoreProjectFromSnapshot(commitHash: string): Promise<void> {
115
+ const repo = this.shadowGitRepository;
116
+ await repo.raw(['restore', '--source', commitHash, '.']);
117
+ // Removes any untracked files that were introduced post snapshot.
118
+ await repo.clean('f', ['-d']);
119
+ }
120
+ }
projects/ui/qwen-code/packages/core/src/services/loopDetectionService.test.ts ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
8
+ import { Config } from '../config/config.js';
9
+ import { GeminiClient } from '../core/client.js';
10
+ import {
11
+ GeminiEventType,
12
+ ServerGeminiContentEvent,
13
+ ServerGeminiStreamEvent,
14
+ ServerGeminiToolCallRequestEvent,
15
+ } from '../core/turn.js';
16
+ import * as loggers from '../telemetry/loggers.js';
17
+ import { LoopType } from '../telemetry/types.js';
18
+ import { LoopDetectionService } from './loopDetectionService.js';
19
+
20
+ vi.mock('../telemetry/loggers.js', () => ({
21
+ logLoopDetected: vi.fn(),
22
+ logApiError: vi.fn(),
23
+ logApiResponse: vi.fn(),
24
+ }));
25
+
26
+ const TOOL_CALL_LOOP_THRESHOLD = 5;
27
+ const CONTENT_LOOP_THRESHOLD = 10;
28
+ const CONTENT_CHUNK_SIZE = 50;
29
+
30
+ describe('LoopDetectionService', () => {
31
+ let service: LoopDetectionService;
32
+ let mockConfig: Config;
33
+
34
+ beforeEach(() => {
35
+ mockConfig = {
36
+ getTelemetryEnabled: () => true,
37
+ } as unknown as Config;
38
+ service = new LoopDetectionService(mockConfig);
39
+ vi.clearAllMocks();
40
+ });
41
+
42
+ const createToolCallRequestEvent = (
43
+ name: string,
44
+ args: Record<string, unknown>,
45
+ ): ServerGeminiToolCallRequestEvent => ({
46
+ type: GeminiEventType.ToolCallRequest,
47
+ value: {
48
+ name,
49
+ args,
50
+ callId: 'test-id',
51
+ isClientInitiated: false,
52
+ prompt_id: 'test-prompt-id',
53
+ },
54
+ });
55
+
56
+ const createContentEvent = (content: string): ServerGeminiContentEvent => ({
57
+ type: GeminiEventType.Content,
58
+ value: content,
59
+ });
60
+
61
+ const createRepetitiveContent = (id: number, length: number): string => {
62
+ const baseString = `This is a unique sentence, id=${id}. `;
63
+ let content = '';
64
+ while (content.length < length) {
65
+ content += baseString;
66
+ }
67
+ return content.slice(0, length);
68
+ };
69
+
70
+ describe('Tool Call Loop Detection', () => {
71
+ it(`should not detect a loop for fewer than TOOL_CALL_LOOP_THRESHOLD identical calls`, () => {
72
+ const event = createToolCallRequestEvent('testTool', { param: 'value' });
73
+ for (let i = 0; i < TOOL_CALL_LOOP_THRESHOLD - 1; i++) {
74
+ expect(service.addAndCheck(event)).toBe(false);
75
+ }
76
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
77
+ });
78
+
79
+ it(`should detect a loop on the TOOL_CALL_LOOP_THRESHOLD-th identical call`, () => {
80
+ const event = createToolCallRequestEvent('testTool', { param: 'value' });
81
+ for (let i = 0; i < TOOL_CALL_LOOP_THRESHOLD - 1; i++) {
82
+ service.addAndCheck(event);
83
+ }
84
+ expect(service.addAndCheck(event)).toBe(true);
85
+ expect(loggers.logLoopDetected).toHaveBeenCalledTimes(1);
86
+ });
87
+
88
+ it('should detect a loop on subsequent identical calls', () => {
89
+ const event = createToolCallRequestEvent('testTool', { param: 'value' });
90
+ for (let i = 0; i < TOOL_CALL_LOOP_THRESHOLD; i++) {
91
+ service.addAndCheck(event);
92
+ }
93
+ expect(service.addAndCheck(event)).toBe(true);
94
+ expect(loggers.logLoopDetected).toHaveBeenCalledTimes(1);
95
+ });
96
+
97
+ it('should not detect a loop for different tool calls', () => {
98
+ const event1 = createToolCallRequestEvent('testTool', {
99
+ param: 'value1',
100
+ });
101
+ const event2 = createToolCallRequestEvent('testTool', {
102
+ param: 'value2',
103
+ });
104
+ const event3 = createToolCallRequestEvent('anotherTool', {
105
+ param: 'value1',
106
+ });
107
+
108
+ for (let i = 0; i < TOOL_CALL_LOOP_THRESHOLD - 2; i++) {
109
+ expect(service.addAndCheck(event1)).toBe(false);
110
+ expect(service.addAndCheck(event2)).toBe(false);
111
+ expect(service.addAndCheck(event3)).toBe(false);
112
+ }
113
+ });
114
+
115
+ it('should not reset tool call counter for other event types', () => {
116
+ const toolCallEvent = createToolCallRequestEvent('testTool', {
117
+ param: 'value',
118
+ });
119
+ const otherEvent = {
120
+ type: 'thought',
121
+ } as unknown as ServerGeminiStreamEvent;
122
+
123
+ // Send events just below the threshold
124
+ for (let i = 0; i < TOOL_CALL_LOOP_THRESHOLD - 1; i++) {
125
+ expect(service.addAndCheck(toolCallEvent)).toBe(false);
126
+ }
127
+
128
+ // Send a different event type
129
+ expect(service.addAndCheck(otherEvent)).toBe(false);
130
+
131
+ // Send the tool call event again, which should now trigger the loop
132
+ expect(service.addAndCheck(toolCallEvent)).toBe(true);
133
+ expect(loggers.logLoopDetected).toHaveBeenCalledTimes(1);
134
+ });
135
+ });
136
+
137
+ describe('Content Loop Detection', () => {
138
+ const generateRandomString = (length: number) => {
139
+ let result = '';
140
+ const characters =
141
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
142
+ const charactersLength = characters.length;
143
+ for (let i = 0; i < length; i++) {
144
+ result += characters.charAt(
145
+ Math.floor(Math.random() * charactersLength),
146
+ );
147
+ }
148
+ return result;
149
+ };
150
+
151
+ it('should not detect a loop for random content', () => {
152
+ service.reset('');
153
+ for (let i = 0; i < 1000; i++) {
154
+ const content = generateRandomString(10);
155
+ const isLoop = service.addAndCheck(createContentEvent(content));
156
+ expect(isLoop).toBe(false);
157
+ }
158
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
159
+ });
160
+
161
+ it('should detect a loop when a chunk of content repeats consecutively', () => {
162
+ service.reset('');
163
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
164
+
165
+ let isLoop = false;
166
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD; i++) {
167
+ isLoop = service.addAndCheck(createContentEvent(repeatedContent));
168
+ }
169
+ expect(isLoop).toBe(true);
170
+ expect(loggers.logLoopDetected).toHaveBeenCalledTimes(1);
171
+ });
172
+
173
+ it('should not detect a loop if repetitions are very far apart', () => {
174
+ service.reset('');
175
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
176
+ const fillerContent = generateRandomString(500);
177
+
178
+ let isLoop = false;
179
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD; i++) {
180
+ isLoop = service.addAndCheck(createContentEvent(repeatedContent));
181
+ isLoop = service.addAndCheck(createContentEvent(fillerContent));
182
+ }
183
+ expect(isLoop).toBe(false);
184
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
185
+ });
186
+ });
187
+
188
+ describe('Content Loop Detection with Code Blocks', () => {
189
+ it('should not detect a loop when repetitive content is inside a code block', () => {
190
+ service.reset('');
191
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
192
+
193
+ service.addAndCheck(createContentEvent('```\n'));
194
+
195
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD; i++) {
196
+ const isLoop = service.addAndCheck(createContentEvent(repeatedContent));
197
+ expect(isLoop).toBe(false);
198
+ }
199
+
200
+ const isLoop = service.addAndCheck(createContentEvent('\n```'));
201
+ expect(isLoop).toBe(false);
202
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
203
+ });
204
+
205
+ it('should not detect loops when content transitions into a code block', () => {
206
+ service.reset('');
207
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
208
+
209
+ // Add some repetitive content outside of code block
210
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 2; i++) {
211
+ service.addAndCheck(createContentEvent(repeatedContent));
212
+ }
213
+
214
+ // Now transition into a code block - this should prevent loop detection
215
+ // even though we were already close to the threshold
216
+ const codeBlockStart = '```javascript\n';
217
+ const isLoop = service.addAndCheck(createContentEvent(codeBlockStart));
218
+ expect(isLoop).toBe(false);
219
+
220
+ // Continue adding repetitive content inside the code block - should not trigger loop
221
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD; i++) {
222
+ const isLoopInside = service.addAndCheck(
223
+ createContentEvent(repeatedContent),
224
+ );
225
+ expect(isLoopInside).toBe(false);
226
+ }
227
+
228
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
229
+ });
230
+
231
+ it('should skip loop detection when already inside a code block (this.inCodeBlock)', () => {
232
+ service.reset('');
233
+
234
+ // Start with content that puts us inside a code block
235
+ service.addAndCheck(createContentEvent('Here is some code:\n```\n'));
236
+
237
+ // Verify we are now inside a code block and any content should be ignored for loop detection
238
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
239
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD + 5; i++) {
240
+ const isLoop = service.addAndCheck(createContentEvent(repeatedContent));
241
+ expect(isLoop).toBe(false);
242
+ }
243
+
244
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
245
+ });
246
+
247
+ it('should correctly track inCodeBlock state with multiple fence transitions', () => {
248
+ service.reset('');
249
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
250
+
251
+ // Outside code block - should track content
252
+ service.addAndCheck(createContentEvent('Normal text '));
253
+
254
+ // Enter code block (1 fence) - should stop tracking
255
+ const enterResult = service.addAndCheck(createContentEvent('```\n'));
256
+ expect(enterResult).toBe(false);
257
+
258
+ // Inside code block - should not track loops
259
+ for (let i = 0; i < 5; i++) {
260
+ const insideResult = service.addAndCheck(
261
+ createContentEvent(repeatedContent),
262
+ );
263
+ expect(insideResult).toBe(false);
264
+ }
265
+
266
+ // Exit code block (2nd fence) - should reset tracking but still return false
267
+ const exitResult = service.addAndCheck(createContentEvent('```\n'));
268
+ expect(exitResult).toBe(false);
269
+
270
+ // Enter code block again (3rd fence) - should stop tracking again
271
+ const reenterResult = service.addAndCheck(
272
+ createContentEvent('```python\n'),
273
+ );
274
+ expect(reenterResult).toBe(false);
275
+
276
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
277
+ });
278
+
279
+ it('should detect a loop when repetitive content is outside a code block', () => {
280
+ service.reset('');
281
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
282
+
283
+ service.addAndCheck(createContentEvent('```'));
284
+ service.addAndCheck(createContentEvent('\nsome code\n'));
285
+ service.addAndCheck(createContentEvent('```'));
286
+
287
+ let isLoop = false;
288
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD; i++) {
289
+ isLoop = service.addAndCheck(createContentEvent(repeatedContent));
290
+ }
291
+ expect(isLoop).toBe(true);
292
+ expect(loggers.logLoopDetected).toHaveBeenCalledTimes(1);
293
+ });
294
+
295
+ it('should handle content with multiple code blocks and no loops', () => {
296
+ service.reset('');
297
+ service.addAndCheck(createContentEvent('```\ncode1\n```'));
298
+ service.addAndCheck(createContentEvent('\nsome text\n'));
299
+ const isLoop = service.addAndCheck(createContentEvent('```\ncode2\n```'));
300
+
301
+ expect(isLoop).toBe(false);
302
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
303
+ });
304
+
305
+ it('should handle content with mixed code blocks and looping text', () => {
306
+ service.reset('');
307
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
308
+
309
+ service.addAndCheck(createContentEvent('```'));
310
+ service.addAndCheck(createContentEvent('\ncode1\n'));
311
+ service.addAndCheck(createContentEvent('```'));
312
+
313
+ let isLoop = false;
314
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD; i++) {
315
+ isLoop = service.addAndCheck(createContentEvent(repeatedContent));
316
+ }
317
+
318
+ expect(isLoop).toBe(true);
319
+ expect(loggers.logLoopDetected).toHaveBeenCalledTimes(1);
320
+ });
321
+
322
+ it('should not detect a loop for a long code block with some repeating tokens', () => {
323
+ service.reset('');
324
+ const repeatingTokens =
325
+ 'for (let i = 0; i < 10; i++) { console.log(i); }';
326
+
327
+ service.addAndCheck(createContentEvent('```\n'));
328
+
329
+ for (let i = 0; i < 20; i++) {
330
+ const isLoop = service.addAndCheck(createContentEvent(repeatingTokens));
331
+ expect(isLoop).toBe(false);
332
+ }
333
+
334
+ const isLoop = service.addAndCheck(createContentEvent('\n```'));
335
+ expect(isLoop).toBe(false);
336
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
337
+ });
338
+
339
+ it('should reset tracking when a code fence is found', () => {
340
+ service.reset('');
341
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
342
+
343
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
344
+ service.addAndCheck(createContentEvent(repeatedContent));
345
+ }
346
+
347
+ // This should not trigger a loop because of the reset
348
+ service.addAndCheck(createContentEvent('```'));
349
+
350
+ // We are now in a code block, so loop detection should be off.
351
+ // Let's add the repeated content again, it should not trigger a loop.
352
+ let isLoop = false;
353
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD; i++) {
354
+ isLoop = service.addAndCheck(createContentEvent(repeatedContent));
355
+ expect(isLoop).toBe(false);
356
+ }
357
+
358
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
359
+ });
360
+ it('should reset tracking when a table is detected', () => {
361
+ service.reset('');
362
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
363
+
364
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
365
+ service.addAndCheck(createContentEvent(repeatedContent));
366
+ }
367
+
368
+ // This should reset tracking and not trigger a loop
369
+ service.addAndCheck(createContentEvent('| Column 1 | Column 2 |'));
370
+
371
+ // Add more repeated content after table - should not trigger loop
372
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
373
+ const isLoop = service.addAndCheck(createContentEvent(repeatedContent));
374
+ expect(isLoop).toBe(false);
375
+ }
376
+
377
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
378
+ });
379
+
380
+ it('should reset tracking when a list item is detected', () => {
381
+ service.reset('');
382
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
383
+
384
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
385
+ service.addAndCheck(createContentEvent(repeatedContent));
386
+ }
387
+
388
+ // This should reset tracking and not trigger a loop
389
+ service.addAndCheck(createContentEvent('* List item'));
390
+
391
+ // Add more repeated content after list - should not trigger loop
392
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
393
+ const isLoop = service.addAndCheck(createContentEvent(repeatedContent));
394
+ expect(isLoop).toBe(false);
395
+ }
396
+
397
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
398
+ });
399
+
400
+ it('should reset tracking when a heading is detected', () => {
401
+ service.reset('');
402
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
403
+
404
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
405
+ service.addAndCheck(createContentEvent(repeatedContent));
406
+ }
407
+
408
+ // This should reset tracking and not trigger a loop
409
+ service.addAndCheck(createContentEvent('## Heading'));
410
+
411
+ // Add more repeated content after heading - should not trigger loop
412
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
413
+ const isLoop = service.addAndCheck(createContentEvent(repeatedContent));
414
+ expect(isLoop).toBe(false);
415
+ }
416
+
417
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
418
+ });
419
+
420
+ it('should reset tracking when a blockquote is detected', () => {
421
+ service.reset('');
422
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
423
+
424
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
425
+ service.addAndCheck(createContentEvent(repeatedContent));
426
+ }
427
+
428
+ // This should reset tracking and not trigger a loop
429
+ service.addAndCheck(createContentEvent('> Quote text'));
430
+
431
+ // Add more repeated content after blockquote - should not trigger loop
432
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
433
+ const isLoop = service.addAndCheck(createContentEvent(repeatedContent));
434
+ expect(isLoop).toBe(false);
435
+ }
436
+
437
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
438
+ });
439
+
440
+ it('should reset tracking for various list item formats', () => {
441
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
442
+
443
+ // Test different list formats - make sure they start at beginning of line
444
+ const listFormats = [
445
+ '* Bullet item',
446
+ '- Dash item',
447
+ '+ Plus item',
448
+ '1. Numbered item',
449
+ '42. Another numbered item',
450
+ ];
451
+
452
+ listFormats.forEach((listFormat, index) => {
453
+ service.reset('');
454
+
455
+ // Build up to near threshold
456
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
457
+ service.addAndCheck(createContentEvent(repeatedContent));
458
+ }
459
+
460
+ // Reset should occur with list item - add newline to ensure it starts at beginning
461
+ service.addAndCheck(createContentEvent('\n' + listFormat));
462
+
463
+ // Should not trigger loop after reset - use different content to avoid any cached state issues
464
+ const newRepeatedContent = createRepetitiveContent(
465
+ index + 100,
466
+ CONTENT_CHUNK_SIZE,
467
+ );
468
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
469
+ const isLoop = service.addAndCheck(
470
+ createContentEvent(newRepeatedContent),
471
+ );
472
+ expect(isLoop).toBe(false);
473
+ }
474
+ });
475
+
476
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
477
+ });
478
+
479
+ it('should reset tracking for various table formats', () => {
480
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
481
+
482
+ const tableFormats = [
483
+ '| Column 1 | Column 2 |',
484
+ '|---|---|',
485
+ '|++|++|',
486
+ '+---+---+',
487
+ ];
488
+
489
+ tableFormats.forEach((tableFormat, index) => {
490
+ service.reset('');
491
+
492
+ // Build up to near threshold
493
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
494
+ service.addAndCheck(createContentEvent(repeatedContent));
495
+ }
496
+
497
+ // Reset should occur with table format - add newline to ensure it starts at beginning
498
+ service.addAndCheck(createContentEvent('\n' + tableFormat));
499
+
500
+ // Should not trigger loop after reset - use different content to avoid any cached state issues
501
+ const newRepeatedContent = createRepetitiveContent(
502
+ index + 200,
503
+ CONTENT_CHUNK_SIZE,
504
+ );
505
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
506
+ const isLoop = service.addAndCheck(
507
+ createContentEvent(newRepeatedContent),
508
+ );
509
+ expect(isLoop).toBe(false);
510
+ }
511
+ });
512
+
513
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
514
+ });
515
+
516
+ it('should reset tracking for various heading levels', () => {
517
+ const repeatedContent = createRepetitiveContent(1, CONTENT_CHUNK_SIZE);
518
+
519
+ const headingFormats = [
520
+ '# H1 Heading',
521
+ '## H2 Heading',
522
+ '### H3 Heading',
523
+ '#### H4 Heading',
524
+ '##### H5 Heading',
525
+ '###### H6 Heading',
526
+ ];
527
+
528
+ headingFormats.forEach((headingFormat, index) => {
529
+ service.reset('');
530
+
531
+ // Build up to near threshold
532
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
533
+ service.addAndCheck(createContentEvent(repeatedContent));
534
+ }
535
+
536
+ // Reset should occur with heading - add newline to ensure it starts at beginning
537
+ service.addAndCheck(createContentEvent('\n' + headingFormat));
538
+
539
+ // Should not trigger loop after reset - use different content to avoid any cached state issues
540
+ const newRepeatedContent = createRepetitiveContent(
541
+ index + 300,
542
+ CONTENT_CHUNK_SIZE,
543
+ );
544
+ for (let i = 0; i < CONTENT_LOOP_THRESHOLD - 1; i++) {
545
+ const isLoop = service.addAndCheck(
546
+ createContentEvent(newRepeatedContent),
547
+ );
548
+ expect(isLoop).toBe(false);
549
+ }
550
+ });
551
+
552
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
553
+ });
554
+ });
555
+
556
+ describe('Edge Cases', () => {
557
+ it('should handle empty content', () => {
558
+ const event = createContentEvent('');
559
+ expect(service.addAndCheck(event)).toBe(false);
560
+ });
561
+ });
562
+
563
+ describe('Reset Functionality', () => {
564
+ it('tool call should reset content count', () => {
565
+ const contentEvent = createContentEvent('Some content.');
566
+ const toolEvent = createToolCallRequestEvent('testTool', {
567
+ param: 'value',
568
+ });
569
+ for (let i = 0; i < 9; i++) {
570
+ service.addAndCheck(contentEvent);
571
+ }
572
+
573
+ service.addAndCheck(toolEvent);
574
+
575
+ // Should start fresh
576
+ expect(service.addAndCheck(createContentEvent('Fresh content.'))).toBe(
577
+ false,
578
+ );
579
+ });
580
+ });
581
+
582
+ describe('General Behavior', () => {
583
+ it('should return false for unhandled event types', () => {
584
+ const otherEvent = {
585
+ type: 'unhandled_event',
586
+ } as unknown as ServerGeminiStreamEvent;
587
+ expect(service.addAndCheck(otherEvent)).toBe(false);
588
+ expect(service.addAndCheck(otherEvent)).toBe(false);
589
+ });
590
+ });
591
+ });
592
+
593
+ describe('LoopDetectionService LLM Checks', () => {
594
+ let service: LoopDetectionService;
595
+ let mockConfig: Config;
596
+ let mockGeminiClient: GeminiClient;
597
+ let abortController: AbortController;
598
+
599
+ beforeEach(() => {
600
+ mockGeminiClient = {
601
+ getHistory: vi.fn().mockReturnValue([]),
602
+ generateJson: vi.fn(),
603
+ } as unknown as GeminiClient;
604
+
605
+ mockConfig = {
606
+ getGeminiClient: () => mockGeminiClient,
607
+ getDebugMode: () => false,
608
+ getTelemetryEnabled: () => true,
609
+ } as unknown as Config;
610
+
611
+ service = new LoopDetectionService(mockConfig);
612
+ abortController = new AbortController();
613
+ vi.clearAllMocks();
614
+ });
615
+
616
+ afterEach(() => {
617
+ vi.restoreAllMocks();
618
+ });
619
+
620
+ const advanceTurns = async (count: number) => {
621
+ for (let i = 0; i < count; i++) {
622
+ await service.turnStarted(abortController.signal);
623
+ }
624
+ };
625
+
626
+ it('should not trigger LLM check before LLM_CHECK_AFTER_TURNS', async () => {
627
+ await advanceTurns(29);
628
+ expect(mockGeminiClient.generateJson).not.toHaveBeenCalled();
629
+ });
630
+
631
+ it('should trigger LLM check on the 30th turn', async () => {
632
+ mockGeminiClient.generateJson = vi
633
+ .fn()
634
+ .mockResolvedValue({ confidence: 0.1 });
635
+ await advanceTurns(30);
636
+ expect(mockGeminiClient.generateJson).toHaveBeenCalledTimes(1);
637
+ });
638
+
639
+ it('should detect a cognitive loop when confidence is high', async () => {
640
+ // First check at turn 30
641
+ mockGeminiClient.generateJson = vi
642
+ .fn()
643
+ .mockResolvedValue({ confidence: 0.85, reasoning: 'Repetitive actions' });
644
+ await advanceTurns(30);
645
+ expect(mockGeminiClient.generateJson).toHaveBeenCalledTimes(1);
646
+
647
+ // The confidence of 0.85 will result in a low interval.
648
+ // The interval will be: 5 + (15 - 5) * (1 - 0.85) = 5 + 10 * 0.15 = 6.5 -> rounded to 7
649
+ await advanceTurns(6); // advance to turn 36
650
+
651
+ mockGeminiClient.generateJson = vi
652
+ .fn()
653
+ .mockResolvedValue({ confidence: 0.95, reasoning: 'Repetitive actions' });
654
+ const finalResult = await service.turnStarted(abortController.signal); // This is turn 37
655
+
656
+ expect(finalResult).toBe(true);
657
+ expect(loggers.logLoopDetected).toHaveBeenCalledWith(
658
+ mockConfig,
659
+ expect.objectContaining({
660
+ 'event.name': 'loop_detected',
661
+ loop_type: LoopType.LLM_DETECTED_LOOP,
662
+ }),
663
+ );
664
+ });
665
+
666
+ it('should not detect a loop when confidence is low', async () => {
667
+ mockGeminiClient.generateJson = vi
668
+ .fn()
669
+ .mockResolvedValue({ confidence: 0.5, reasoning: 'Looks okay' });
670
+ await advanceTurns(30);
671
+ const result = await service.turnStarted(abortController.signal);
672
+ expect(result).toBe(false);
673
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
674
+ });
675
+
676
+ it('should adjust the check interval based on confidence', async () => {
677
+ // Confidence is 0.0, so interval should be MAX_LLM_CHECK_INTERVAL (15)
678
+ mockGeminiClient.generateJson = vi
679
+ .fn()
680
+ .mockResolvedValue({ confidence: 0.0 });
681
+ await advanceTurns(30); // First check at turn 30
682
+ expect(mockGeminiClient.generateJson).toHaveBeenCalledTimes(1);
683
+
684
+ await advanceTurns(14); // Advance to turn 44
685
+ expect(mockGeminiClient.generateJson).toHaveBeenCalledTimes(1);
686
+
687
+ await service.turnStarted(abortController.signal); // Turn 45
688
+ expect(mockGeminiClient.generateJson).toHaveBeenCalledTimes(2);
689
+ });
690
+
691
+ it('should handle errors from generateJson gracefully', async () => {
692
+ mockGeminiClient.generateJson = vi
693
+ .fn()
694
+ .mockRejectedValue(new Error('API error'));
695
+ await advanceTurns(30);
696
+ const result = await service.turnStarted(abortController.signal);
697
+ expect(result).toBe(false);
698
+ expect(loggers.logLoopDetected).not.toHaveBeenCalled();
699
+ });
700
+ });
projects/ui/qwen-code/packages/core/src/services/loopDetectionService.ts ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { createHash } from 'crypto';
8
+ import { GeminiEventType, ServerGeminiStreamEvent } from '../core/turn.js';
9
+ import { logLoopDetected } from '../telemetry/loggers.js';
10
+ import { LoopDetectedEvent, LoopType } from '../telemetry/types.js';
11
+ import { Config, DEFAULT_GEMINI_FLASH_MODEL } from '../config/config.js';
12
+
13
+ const TOOL_CALL_LOOP_THRESHOLD = 5;
14
+ const CONTENT_LOOP_THRESHOLD = 10;
15
+ const CONTENT_CHUNK_SIZE = 50;
16
+ const MAX_HISTORY_LENGTH = 1000;
17
+
18
+ /**
19
+ * The number of recent conversation turns to include in the history when asking the LLM to check for a loop.
20
+ */
21
+ const LLM_LOOP_CHECK_HISTORY_COUNT = 20;
22
+
23
+ /**
24
+ * The number of turns that must pass in a single prompt before the LLM-based loop check is activated.
25
+ */
26
+ const LLM_CHECK_AFTER_TURNS = 30;
27
+
28
+ /**
29
+ * The default interval, in number of turns, at which the LLM-based loop check is performed.
30
+ * This value is adjusted dynamically based on the LLM's confidence.
31
+ */
32
+ const DEFAULT_LLM_CHECK_INTERVAL = 3;
33
+
34
+ /**
35
+ * The minimum interval for LLM-based loop checks.
36
+ * This is used when the confidence of a loop is high, to check more frequently.
37
+ */
38
+ const MIN_LLM_CHECK_INTERVAL = 5;
39
+
40
+ /**
41
+ * The maximum interval for LLM-based loop checks.
42
+ * This is used when the confidence of a loop is low, to check less frequently.
43
+ */
44
+ const MAX_LLM_CHECK_INTERVAL = 15;
45
+
46
+ /**
47
+ * Service for detecting and preventing infinite loops in AI responses.
48
+ * Monitors tool call repetitions and content sentence repetitions.
49
+ */
50
+ export class LoopDetectionService {
51
+ private readonly config: Config;
52
+ private promptId = '';
53
+
54
+ // Tool call tracking
55
+ private lastToolCallKey: string | null = null;
56
+ private toolCallRepetitionCount: number = 0;
57
+
58
+ // Content streaming tracking
59
+ private streamContentHistory = '';
60
+ private contentStats = new Map<string, number[]>();
61
+ private lastContentIndex = 0;
62
+ private loopDetected = false;
63
+ private inCodeBlock = false;
64
+
65
+ // LLM loop track tracking
66
+ private turnsInCurrentPrompt = 0;
67
+ private llmCheckInterval = DEFAULT_LLM_CHECK_INTERVAL;
68
+ private lastCheckTurn = 0;
69
+
70
+ constructor(config: Config) {
71
+ this.config = config;
72
+ }
73
+
74
+ private getToolCallKey(toolCall: { name: string; args: object }): string {
75
+ const argsString = JSON.stringify(toolCall.args);
76
+ const keyString = `${toolCall.name}:${argsString}`;
77
+ return createHash('sha256').update(keyString).digest('hex');
78
+ }
79
+
80
+ /**
81
+ * Processes a stream event and checks for loop conditions.
82
+ * @param event - The stream event to process
83
+ * @returns true if a loop is detected, false otherwise
84
+ */
85
+ addAndCheck(event: ServerGeminiStreamEvent): boolean {
86
+ if (this.loopDetected) {
87
+ return true;
88
+ }
89
+
90
+ switch (event.type) {
91
+ case GeminiEventType.ToolCallRequest:
92
+ // content chanting only happens in one single stream, reset if there
93
+ // is a tool call in between
94
+ this.resetContentTracking();
95
+ this.loopDetected = this.checkToolCallLoop(event.value);
96
+ break;
97
+ case GeminiEventType.Content:
98
+ this.loopDetected = this.checkContentLoop(event.value);
99
+ break;
100
+ default:
101
+ break;
102
+ }
103
+ return this.loopDetected;
104
+ }
105
+
106
+ /**
107
+ * Signals the start of a new turn in the conversation.
108
+ *
109
+ * This method increments the turn counter and, if specific conditions are met,
110
+ * triggers an LLM-based check to detect potential conversation loops. The check
111
+ * is performed periodically based on the `llmCheckInterval`.
112
+ *
113
+ * @param signal - An AbortSignal to allow for cancellation of the asynchronous LLM check.
114
+ * @returns A promise that resolves to `true` if a loop is detected, and `false` otherwise.
115
+ */
116
+ async turnStarted(signal: AbortSignal) {
117
+ this.turnsInCurrentPrompt++;
118
+
119
+ if (
120
+ this.turnsInCurrentPrompt >= LLM_CHECK_AFTER_TURNS &&
121
+ this.turnsInCurrentPrompt - this.lastCheckTurn >= this.llmCheckInterval
122
+ ) {
123
+ this.lastCheckTurn = this.turnsInCurrentPrompt;
124
+ return await this.checkForLoopWithLLM(signal);
125
+ }
126
+
127
+ return false;
128
+ }
129
+
130
+ private checkToolCallLoop(toolCall: { name: string; args: object }): boolean {
131
+ const key = this.getToolCallKey(toolCall);
132
+ if (this.lastToolCallKey === key) {
133
+ this.toolCallRepetitionCount++;
134
+ } else {
135
+ this.lastToolCallKey = key;
136
+ this.toolCallRepetitionCount = 1;
137
+ }
138
+ if (this.toolCallRepetitionCount >= TOOL_CALL_LOOP_THRESHOLD) {
139
+ logLoopDetected(
140
+ this.config,
141
+ new LoopDetectedEvent(
142
+ LoopType.CONSECUTIVE_IDENTICAL_TOOL_CALLS,
143
+ this.promptId,
144
+ ),
145
+ );
146
+ return true;
147
+ }
148
+ return false;
149
+ }
150
+
151
+ /**
152
+ * Detects content loops by analyzing streaming text for repetitive patterns.
153
+ *
154
+ * The algorithm works by:
155
+ * 1. Appending new content to the streaming history
156
+ * 2. Truncating history if it exceeds the maximum length
157
+ * 3. Analyzing content chunks for repetitive patterns using hashing
158
+ * 4. Detecting loops when identical chunks appear frequently within a short distance
159
+ * 5. Disabling loop detection within code blocks to prevent false positives,
160
+ * as repetitive code structures are common and not necessarily loops.
161
+ */
162
+ private checkContentLoop(content: string): boolean {
163
+ // Different content elements can often contain repetitive syntax that is not indicative of a loop.
164
+ // To avoid false positives, we detect when we encounter different content types and
165
+ // reset tracking to avoid analyzing content that spans across different element boundaries.
166
+ const numFences = (content.match(/```/g) ?? []).length;
167
+ const hasTable = /(^|\n)\s*(\|.*\||[|+-]{3,})/.test(content);
168
+ const hasListItem =
169
+ /(^|\n)\s*[*-+]\s/.test(content) || /(^|\n)\s*\d+\.\s/.test(content);
170
+ const hasHeading = /(^|\n)#+\s/.test(content);
171
+ const hasBlockquote = /(^|\n)>\s/.test(content);
172
+
173
+ if (numFences || hasTable || hasListItem || hasHeading || hasBlockquote) {
174
+ // Reset tracking when different content elements are detected to avoid analyzing content
175
+ // that spans across different element boundaries.
176
+ this.resetContentTracking();
177
+ }
178
+
179
+ const wasInCodeBlock = this.inCodeBlock;
180
+ this.inCodeBlock =
181
+ numFences % 2 === 0 ? this.inCodeBlock : !this.inCodeBlock;
182
+ if (wasInCodeBlock || this.inCodeBlock) {
183
+ return false;
184
+ }
185
+
186
+ this.streamContentHistory += content;
187
+
188
+ this.truncateAndUpdate();
189
+ return this.analyzeContentChunksForLoop();
190
+ }
191
+
192
+ /**
193
+ * Truncates the content history to prevent unbounded memory growth.
194
+ * When truncating, adjusts all stored indices to maintain their relative positions.
195
+ */
196
+ private truncateAndUpdate(): void {
197
+ if (this.streamContentHistory.length <= MAX_HISTORY_LENGTH) {
198
+ return;
199
+ }
200
+
201
+ // Calculate how much content to remove from the beginning
202
+ const truncationAmount =
203
+ this.streamContentHistory.length - MAX_HISTORY_LENGTH;
204
+ this.streamContentHistory =
205
+ this.streamContentHistory.slice(truncationAmount);
206
+ this.lastContentIndex = Math.max(
207
+ 0,
208
+ this.lastContentIndex - truncationAmount,
209
+ );
210
+
211
+ // Update all stored chunk indices to account for the truncation
212
+ for (const [hash, oldIndices] of this.contentStats.entries()) {
213
+ const adjustedIndices = oldIndices
214
+ .map((index) => index - truncationAmount)
215
+ .filter((index) => index >= 0);
216
+
217
+ if (adjustedIndices.length > 0) {
218
+ this.contentStats.set(hash, adjustedIndices);
219
+ } else {
220
+ this.contentStats.delete(hash);
221
+ }
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Analyzes content in fixed-size chunks to detect repetitive patterns.
227
+ *
228
+ * Uses a sliding window approach:
229
+ * 1. Extract chunks of fixed size (CONTENT_CHUNK_SIZE)
230
+ * 2. Hash each chunk for efficient comparison
231
+ * 3. Track positions where identical chunks appear
232
+ * 4. Detect loops when chunks repeat frequently within a short distance
233
+ */
234
+ private analyzeContentChunksForLoop(): boolean {
235
+ while (this.hasMoreChunksToProcess()) {
236
+ // Extract current chunk of text
237
+ const currentChunk = this.streamContentHistory.substring(
238
+ this.lastContentIndex,
239
+ this.lastContentIndex + CONTENT_CHUNK_SIZE,
240
+ );
241
+ const chunkHash = createHash('sha256').update(currentChunk).digest('hex');
242
+
243
+ if (this.isLoopDetectedForChunk(currentChunk, chunkHash)) {
244
+ logLoopDetected(
245
+ this.config,
246
+ new LoopDetectedEvent(
247
+ LoopType.CHANTING_IDENTICAL_SENTENCES,
248
+ this.promptId,
249
+ ),
250
+ );
251
+ return true;
252
+ }
253
+
254
+ // Move to next position in the sliding window
255
+ this.lastContentIndex++;
256
+ }
257
+
258
+ return false;
259
+ }
260
+
261
+ private hasMoreChunksToProcess(): boolean {
262
+ return (
263
+ this.lastContentIndex + CONTENT_CHUNK_SIZE <=
264
+ this.streamContentHistory.length
265
+ );
266
+ }
267
+
268
+ /**
269
+ * Determines if a content chunk indicates a loop pattern.
270
+ *
271
+ * Loop detection logic:
272
+ * 1. Check if we've seen this hash before (new chunks are stored for future comparison)
273
+ * 2. Verify actual content matches to prevent hash collisions
274
+ * 3. Track all positions where this chunk appears
275
+ * 4. A loop is detected when the same chunk appears CONTENT_LOOP_THRESHOLD times
276
+ * within a small average distance (≤ 1.5 * chunk size)
277
+ */
278
+ private isLoopDetectedForChunk(chunk: string, hash: string): boolean {
279
+ const existingIndices = this.contentStats.get(hash);
280
+
281
+ if (!existingIndices) {
282
+ this.contentStats.set(hash, [this.lastContentIndex]);
283
+ return false;
284
+ }
285
+
286
+ if (!this.isActualContentMatch(chunk, existingIndices[0])) {
287
+ return false;
288
+ }
289
+
290
+ existingIndices.push(this.lastContentIndex);
291
+
292
+ if (existingIndices.length < CONTENT_LOOP_THRESHOLD) {
293
+ return false;
294
+ }
295
+
296
+ // Analyze the most recent occurrences to see if they're clustered closely together
297
+ const recentIndices = existingIndices.slice(-CONTENT_LOOP_THRESHOLD);
298
+ const totalDistance =
299
+ recentIndices[recentIndices.length - 1] - recentIndices[0];
300
+ const averageDistance = totalDistance / (CONTENT_LOOP_THRESHOLD - 1);
301
+ const maxAllowedDistance = CONTENT_CHUNK_SIZE * 1.5;
302
+
303
+ return averageDistance <= maxAllowedDistance;
304
+ }
305
+
306
+ /**
307
+ * Verifies that two chunks with the same hash actually contain identical content.
308
+ * This prevents false positives from hash collisions.
309
+ */
310
+ private isActualContentMatch(
311
+ currentChunk: string,
312
+ originalIndex: number,
313
+ ): boolean {
314
+ const originalChunk = this.streamContentHistory.substring(
315
+ originalIndex,
316
+ originalIndex + CONTENT_CHUNK_SIZE,
317
+ );
318
+ return originalChunk === currentChunk;
319
+ }
320
+
321
+ private async checkForLoopWithLLM(signal: AbortSignal) {
322
+ const recentHistory = this.config
323
+ .getGeminiClient()
324
+ .getHistory()
325
+ .slice(-LLM_LOOP_CHECK_HISTORY_COUNT);
326
+
327
+ const prompt = `You are a sophisticated AI diagnostic agent specializing in identifying when a conversational AI is stuck in an unproductive state. Your task is to analyze the provided conversation history and determine if the assistant has ceased to make meaningful progress.
328
+
329
+ An unproductive state is characterized by one or more of the following patterns over the last 5 or more assistant turns:
330
+
331
+ Repetitive Actions: The assistant repeats the same tool calls or conversational responses a decent number of times. This includes simple loops (e.g., tool_A, tool_A, tool_A) and alternating patterns (e.g., tool_A, tool_B, tool_A, tool_B, ...).
332
+
333
+ Cognitive Loop: The assistant seems unable to determine the next logical step. It might express confusion, repeatedly ask the same questions, or generate responses that don't logically follow from the previous turns, indicating it's stuck and not advancing the task.
334
+
335
+ Crucially, differentiate between a true unproductive state and legitimate, incremental progress.
336
+ For example, a series of 'tool_A' or 'tool_B' tool calls that make small, distinct changes to the same file (like adding docstrings to functions one by one) is considered forward progress and is NOT a loop. A loop would be repeatedly replacing the same text with the same content, or cycling between a small set of files with no net change.
337
+
338
+ Please analyze the conversation history to determine the possibility that the conversation is stuck in a repetitive, non-productive state.`;
339
+ const contents = [
340
+ ...recentHistory,
341
+ { role: 'user', parts: [{ text: prompt }] },
342
+ ];
343
+ const schema: Record<string, unknown> = {
344
+ type: 'object',
345
+ properties: {
346
+ reasoning: {
347
+ type: 'string',
348
+ description:
349
+ 'Your reasoning on if the conversation is looping without forward progress.',
350
+ },
351
+ confidence: {
352
+ type: 'number',
353
+ description:
354
+ 'A number between 0.0 and 1.0 representing your confidence that the conversation is in an unproductive state.',
355
+ },
356
+ },
357
+ required: ['reasoning', 'confidence'],
358
+ };
359
+ let result;
360
+ try {
361
+ result = await this.config
362
+ .getGeminiClient()
363
+ .generateJson(contents, schema, signal, DEFAULT_GEMINI_FLASH_MODEL);
364
+ } catch (e) {
365
+ // Do nothing, treat it as a non-loop.
366
+ this.config.getDebugMode() ? console.error(e) : console.debug(e);
367
+ return false;
368
+ }
369
+
370
+ if (typeof result['confidence'] === 'number') {
371
+ if (result['confidence'] > 0.9) {
372
+ if (typeof result['reasoning'] === 'string' && result['reasoning']) {
373
+ console.warn(result['reasoning']);
374
+ }
375
+ logLoopDetected(
376
+ this.config,
377
+ new LoopDetectedEvent(LoopType.LLM_DETECTED_LOOP, this.promptId),
378
+ );
379
+ return true;
380
+ } else {
381
+ this.llmCheckInterval = Math.round(
382
+ MIN_LLM_CHECK_INTERVAL +
383
+ (MAX_LLM_CHECK_INTERVAL - MIN_LLM_CHECK_INTERVAL) *
384
+ (1 - result['confidence']),
385
+ );
386
+ }
387
+ }
388
+ return false;
389
+ }
390
+
391
+ /**
392
+ * Resets all loop detection state.
393
+ */
394
+ reset(promptId: string): void {
395
+ this.promptId = promptId;
396
+ this.resetToolCallCount();
397
+ this.resetContentTracking();
398
+ this.resetLlmCheckTracking();
399
+ this.loopDetected = false;
400
+ }
401
+
402
+ private resetToolCallCount(): void {
403
+ this.lastToolCallKey = null;
404
+ this.toolCallRepetitionCount = 0;
405
+ }
406
+
407
+ private resetContentTracking(resetHistory = true): void {
408
+ if (resetHistory) {
409
+ this.streamContentHistory = '';
410
+ }
411
+ this.contentStats.clear();
412
+ this.lastContentIndex = 0;
413
+ }
414
+
415
+ private resetLlmCheckTracking(): void {
416
+ this.turnsInCurrentPrompt = 0;
417
+ this.llmCheckInterval = DEFAULT_LLM_CHECK_INTERVAL;
418
+ this.lastCheckTurn = 0;
419
+ }
420
+ }
projects/ui/qwen-code/packages/core/src/services/shellExecutionService.test.ts ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, type Mock } from 'vitest';
8
+ import EventEmitter from 'events';
9
+ import { Readable } from 'stream';
10
+ import { type ChildProcess } from 'child_process';
11
+ import {
12
+ ShellExecutionService,
13
+ ShellOutputEvent,
14
+ } from './shellExecutionService.js';
15
+
16
+ // Hoisted Mocks
17
+ const mockPtySpawn = vi.hoisted(() => vi.fn());
18
+ const mockCpSpawn = vi.hoisted(() => vi.fn());
19
+ const mockIsBinary = vi.hoisted(() => vi.fn());
20
+ const mockPlatform = vi.hoisted(() => vi.fn());
21
+ const mockGetPty = vi.hoisted(() => vi.fn());
22
+
23
+ // Top-level Mocks
24
+ vi.mock('@lydell/node-pty', () => ({
25
+ spawn: mockPtySpawn,
26
+ }));
27
+ vi.mock('child_process', () => ({
28
+ spawn: mockCpSpawn,
29
+ }));
30
+ vi.mock('../utils/textUtils.js', () => ({
31
+ isBinary: mockIsBinary,
32
+ }));
33
+ vi.mock('os', () => ({
34
+ default: {
35
+ platform: mockPlatform,
36
+ constants: {
37
+ signals: {
38
+ SIGTERM: 15,
39
+ SIGKILL: 9,
40
+ },
41
+ },
42
+ },
43
+ platform: mockPlatform,
44
+ constants: {
45
+ signals: {
46
+ SIGTERM: 15,
47
+ SIGKILL: 9,
48
+ },
49
+ },
50
+ }));
51
+ vi.mock('../utils/getPty.js', () => ({
52
+ getPty: mockGetPty,
53
+ }));
54
+
55
+ const mockProcessKill = vi
56
+ .spyOn(process, 'kill')
57
+ .mockImplementation(() => true);
58
+
59
+ describe('ShellExecutionService', () => {
60
+ let mockPtyProcess: EventEmitter & {
61
+ pid: number;
62
+ kill: Mock;
63
+ onData: Mock;
64
+ onExit: Mock;
65
+ };
66
+ let onOutputEventMock: Mock<(event: ShellOutputEvent) => void>;
67
+
68
+ beforeEach(() => {
69
+ vi.clearAllMocks();
70
+
71
+ mockIsBinary.mockReturnValue(false);
72
+ mockPlatform.mockReturnValue('linux');
73
+ mockGetPty.mockResolvedValue({
74
+ module: { spawn: mockPtySpawn },
75
+ name: 'mock-pty',
76
+ });
77
+
78
+ onOutputEventMock = vi.fn();
79
+
80
+ mockPtyProcess = new EventEmitter() as EventEmitter & {
81
+ pid: number;
82
+ kill: Mock;
83
+ onData: Mock;
84
+ onExit: Mock;
85
+ };
86
+ mockPtyProcess.pid = 12345;
87
+ mockPtyProcess.kill = vi.fn();
88
+ mockPtyProcess.onData = vi.fn();
89
+ mockPtyProcess.onExit = vi.fn();
90
+
91
+ mockPtySpawn.mockReturnValue(mockPtyProcess);
92
+ });
93
+
94
+ // Helper function to run a standard execution simulation
95
+ const simulateExecution = async (
96
+ command: string,
97
+ simulation: (
98
+ ptyProcess: typeof mockPtyProcess,
99
+ ac: AbortController,
100
+ ) => void,
101
+ ) => {
102
+ const abortController = new AbortController();
103
+ const handle = await ShellExecutionService.execute(
104
+ command,
105
+ '/test/dir',
106
+ onOutputEventMock,
107
+ abortController.signal,
108
+ true,
109
+ );
110
+
111
+ await new Promise((resolve) => setImmediate(resolve));
112
+ simulation(mockPtyProcess, abortController);
113
+ const result = await handle.result;
114
+ return { result, handle, abortController };
115
+ };
116
+
117
+ describe('Successful Execution', () => {
118
+ it('should execute a command and capture output', async () => {
119
+ const { result, handle } = await simulateExecution('ls -l', (pty) => {
120
+ pty.onData.mock.calls[0][0]('file1.txt\n');
121
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
122
+ });
123
+
124
+ expect(mockPtySpawn).toHaveBeenCalledWith(
125
+ 'bash',
126
+ ['-c', 'ls -l'],
127
+ expect.any(Object),
128
+ );
129
+ expect(result.exitCode).toBe(0);
130
+ expect(result.signal).toBeNull();
131
+ expect(result.error).toBeNull();
132
+ expect(result.aborted).toBe(false);
133
+ expect(result.output).toBe('file1.txt');
134
+ expect(handle.pid).toBe(12345);
135
+
136
+ expect(onOutputEventMock).toHaveBeenCalledWith({
137
+ type: 'data',
138
+ chunk: 'file1.txt',
139
+ });
140
+ });
141
+
142
+ it('should strip ANSI codes from output', async () => {
143
+ const { result } = await simulateExecution('ls --color=auto', (pty) => {
144
+ pty.onData.mock.calls[0][0]('a\u001b[31mred\u001b[0mword');
145
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
146
+ });
147
+
148
+ expect(result.output).toBe('aredword');
149
+ expect(onOutputEventMock).toHaveBeenCalledWith({
150
+ type: 'data',
151
+ chunk: 'aredword',
152
+ });
153
+ });
154
+
155
+ it('should correctly decode multi-byte characters split across chunks', async () => {
156
+ const { result } = await simulateExecution('echo "你好"', (pty) => {
157
+ const multiByteChar = '你好';
158
+ pty.onData.mock.calls[0][0](multiByteChar.slice(0, 1));
159
+ pty.onData.mock.calls[0][0](multiByteChar.slice(1));
160
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
161
+ });
162
+ expect(result.output).toBe('你好');
163
+ });
164
+
165
+ it('should handle commands with no output', async () => {
166
+ const { result } = await simulateExecution('touch file', (pty) => {
167
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
168
+ });
169
+
170
+ expect(result.output).toBe('');
171
+ expect(onOutputEventMock).not.toHaveBeenCalled();
172
+ });
173
+ });
174
+
175
+ describe('Failed Execution', () => {
176
+ it('should capture a non-zero exit code', async () => {
177
+ const { result } = await simulateExecution('a-bad-command', (pty) => {
178
+ pty.onData.mock.calls[0][0]('command not found');
179
+ pty.onExit.mock.calls[0][0]({ exitCode: 127, signal: null });
180
+ });
181
+
182
+ expect(result.exitCode).toBe(127);
183
+ expect(result.output).toBe('command not found');
184
+ expect(result.error).toBeNull();
185
+ });
186
+
187
+ it('should capture a termination signal', async () => {
188
+ const { result } = await simulateExecution('long-process', (pty) => {
189
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: 15 });
190
+ });
191
+
192
+ expect(result.exitCode).toBe(0);
193
+ expect(result.signal).toBe(15);
194
+ });
195
+
196
+ it('should handle a synchronous spawn error', async () => {
197
+ mockGetPty.mockImplementation(() => null);
198
+
199
+ mockCpSpawn.mockImplementation(() => {
200
+ throw new Error('Simulated PTY spawn error');
201
+ });
202
+
203
+ const handle = await ShellExecutionService.execute(
204
+ 'any-command',
205
+ '/test/dir',
206
+ onOutputEventMock,
207
+ new AbortController().signal,
208
+ true,
209
+ );
210
+ const result = await handle.result;
211
+
212
+ expect(result.error).toBeInstanceOf(Error);
213
+ expect(result.error?.message).toContain('Simulated PTY spawn error');
214
+ expect(result.exitCode).toBe(1);
215
+ expect(result.output).toBe('');
216
+ expect(handle.pid).toBeUndefined();
217
+ });
218
+ });
219
+
220
+ describe('Aborting Commands', () => {
221
+ it('should abort a running process and set the aborted flag', async () => {
222
+ const { result } = await simulateExecution(
223
+ 'sleep 10',
224
+ (pty, abortController) => {
225
+ abortController.abort();
226
+ pty.onExit.mock.calls[0][0]({ exitCode: 1, signal: null });
227
+ },
228
+ );
229
+
230
+ expect(result.aborted).toBe(true);
231
+ expect(mockPtyProcess.kill).toHaveBeenCalled();
232
+ });
233
+ });
234
+
235
+ describe('Binary Output', () => {
236
+ it('should detect binary output and switch to progress events', async () => {
237
+ mockIsBinary.mockReturnValueOnce(true);
238
+ const binaryChunk1 = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
239
+ const binaryChunk2 = Buffer.from([0x0d, 0x0a, 0x1a, 0x0a]);
240
+
241
+ const { result } = await simulateExecution('cat image.png', (pty) => {
242
+ pty.onData.mock.calls[0][0](binaryChunk1);
243
+ pty.onData.mock.calls[0][0](binaryChunk2);
244
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
245
+ });
246
+
247
+ expect(result.rawOutput).toEqual(
248
+ Buffer.concat([binaryChunk1, binaryChunk2]),
249
+ );
250
+ expect(onOutputEventMock).toHaveBeenCalledTimes(3);
251
+ expect(onOutputEventMock.mock.calls[0][0]).toEqual({
252
+ type: 'binary_detected',
253
+ });
254
+ expect(onOutputEventMock.mock.calls[1][0]).toEqual({
255
+ type: 'binary_progress',
256
+ bytesReceived: 4,
257
+ });
258
+ expect(onOutputEventMock.mock.calls[2][0]).toEqual({
259
+ type: 'binary_progress',
260
+ bytesReceived: 8,
261
+ });
262
+ });
263
+
264
+ it('should not emit data events after binary is detected', async () => {
265
+ mockIsBinary.mockImplementation((buffer) => buffer.includes(0x00));
266
+
267
+ await simulateExecution('cat mixed_file', (pty) => {
268
+ pty.onData.mock.calls[0][0](Buffer.from('some text'));
269
+ pty.onData.mock.calls[0][0](Buffer.from([0x00, 0x01, 0x02]));
270
+ pty.onData.mock.calls[0][0](Buffer.from('more text'));
271
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
272
+ });
273
+
274
+ const eventTypes = onOutputEventMock.mock.calls.map(
275
+ (call: [ShellOutputEvent]) => call[0].type,
276
+ );
277
+ expect(eventTypes).toEqual([
278
+ 'data',
279
+ 'binary_detected',
280
+ 'binary_progress',
281
+ 'binary_progress',
282
+ ]);
283
+ });
284
+ });
285
+
286
+ describe('Platform-Specific Behavior', () => {
287
+ it('should use cmd.exe on Windows', async () => {
288
+ mockPlatform.mockReturnValue('win32');
289
+ await simulateExecution('dir "foo bar"', (pty) =>
290
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null }),
291
+ );
292
+
293
+ expect(mockPtySpawn).toHaveBeenCalledWith(
294
+ 'cmd.exe',
295
+ ['/c', 'dir "foo bar"'],
296
+ expect.any(Object),
297
+ );
298
+ });
299
+
300
+ it('should use bash on Linux', async () => {
301
+ mockPlatform.mockReturnValue('linux');
302
+ await simulateExecution('ls "foo bar"', (pty) =>
303
+ pty.onExit.mock.calls[0][0]({ exitCode: 0, signal: null }),
304
+ );
305
+
306
+ expect(mockPtySpawn).toHaveBeenCalledWith(
307
+ 'bash',
308
+ ['-c', 'ls "foo bar"'],
309
+ expect.any(Object),
310
+ );
311
+ });
312
+ });
313
+ });
314
+
315
+ describe('ShellExecutionService child_process fallback', () => {
316
+ let mockChildProcess: EventEmitter & Partial<ChildProcess>;
317
+ let onOutputEventMock: Mock<(event: ShellOutputEvent) => void>;
318
+
319
+ beforeEach(() => {
320
+ vi.clearAllMocks();
321
+
322
+ mockIsBinary.mockReturnValue(false);
323
+ mockPlatform.mockReturnValue('linux');
324
+ mockGetPty.mockResolvedValue(null);
325
+
326
+ onOutputEventMock = vi.fn();
327
+
328
+ mockChildProcess = new EventEmitter() as EventEmitter &
329
+ Partial<ChildProcess>;
330
+ mockChildProcess.stdout = new EventEmitter() as Readable;
331
+ mockChildProcess.stderr = new EventEmitter() as Readable;
332
+ mockChildProcess.kill = vi.fn();
333
+
334
+ Object.defineProperty(mockChildProcess, 'pid', {
335
+ value: 12345,
336
+ configurable: true,
337
+ });
338
+
339
+ mockCpSpawn.mockReturnValue(mockChildProcess);
340
+ });
341
+
342
+ // Helper function to run a standard execution simulation
343
+ const simulateExecution = async (
344
+ command: string,
345
+ simulation: (cp: typeof mockChildProcess, ac: AbortController) => void,
346
+ ) => {
347
+ const abortController = new AbortController();
348
+ const handle = await ShellExecutionService.execute(
349
+ command,
350
+ '/test/dir',
351
+ onOutputEventMock,
352
+ abortController.signal,
353
+ true,
354
+ );
355
+
356
+ await new Promise((resolve) => setImmediate(resolve));
357
+ simulation(mockChildProcess, abortController);
358
+ const result = await handle.result;
359
+ return { result, handle, abortController };
360
+ };
361
+
362
+ describe('Successful Execution', () => {
363
+ it('should execute a command and capture stdout and stderr', async () => {
364
+ const { result, handle } = await simulateExecution('ls -l', (cp) => {
365
+ cp.stdout?.emit('data', Buffer.from('file1.txt\n'));
366
+ cp.stderr?.emit('data', Buffer.from('a warning'));
367
+ cp.emit('exit', 0, null);
368
+ });
369
+
370
+ expect(mockCpSpawn).toHaveBeenCalledWith(
371
+ 'ls -l',
372
+ [],
373
+ expect.objectContaining({ shell: 'bash' }),
374
+ );
375
+ expect(result.exitCode).toBe(0);
376
+ expect(result.signal).toBeNull();
377
+ expect(result.error).toBeNull();
378
+ expect(result.aborted).toBe(false);
379
+ expect(result.output).toBe('file1.txt\na warning');
380
+ expect(handle.pid).toBe(12345);
381
+
382
+ expect(onOutputEventMock).toHaveBeenCalledWith({
383
+ type: 'data',
384
+ chunk: 'file1.txt\n',
385
+ });
386
+ expect(onOutputEventMock).toHaveBeenCalledWith({
387
+ type: 'data',
388
+ chunk: 'a warning',
389
+ });
390
+ });
391
+
392
+ it('should strip ANSI codes from output', async () => {
393
+ const { result } = await simulateExecution('ls --color=auto', (cp) => {
394
+ cp.stdout?.emit('data', Buffer.from('a\u001b[31mred\u001b[0mword'));
395
+ cp.emit('exit', 0, null);
396
+ });
397
+
398
+ expect(result.output).toBe('aredword');
399
+ expect(onOutputEventMock).toHaveBeenCalledWith({
400
+ type: 'data',
401
+ chunk: 'aredword',
402
+ });
403
+ });
404
+
405
+ it('should correctly decode multi-byte characters split across chunks', async () => {
406
+ const { result } = await simulateExecution('echo "你好"', (cp) => {
407
+ const multiByteChar = Buffer.from('你好', 'utf-8');
408
+ cp.stdout?.emit('data', multiByteChar.slice(0, 2));
409
+ cp.stdout?.emit('data', multiByteChar.slice(2));
410
+ cp.emit('exit', 0, null);
411
+ });
412
+ expect(result.output).toBe('你好');
413
+ });
414
+
415
+ it('should handle commands with no output', async () => {
416
+ const { result } = await simulateExecution('touch file', (cp) => {
417
+ cp.emit('exit', 0, null);
418
+ });
419
+
420
+ expect(result.output).toBe('');
421
+ expect(onOutputEventMock).not.toHaveBeenCalled();
422
+ });
423
+ });
424
+
425
+ describe('Failed Execution', () => {
426
+ it('should capture a non-zero exit code and format output correctly', async () => {
427
+ const { result } = await simulateExecution('a-bad-command', (cp) => {
428
+ cp.stderr?.emit('data', Buffer.from('command not found'));
429
+ cp.emit('exit', 127, null);
430
+ });
431
+
432
+ expect(result.exitCode).toBe(127);
433
+ expect(result.output).toBe('command not found');
434
+ expect(result.error).toBeNull();
435
+ });
436
+
437
+ it('should capture a termination signal', async () => {
438
+ const { result } = await simulateExecution('long-process', (cp) => {
439
+ cp.emit('exit', null, 'SIGTERM');
440
+ });
441
+
442
+ expect(result.exitCode).toBeNull();
443
+ expect(result.signal).toBe(15);
444
+ });
445
+
446
+ it('should handle a spawn error', async () => {
447
+ const spawnError = new Error('spawn EACCES');
448
+ const { result } = await simulateExecution('protected-cmd', (cp) => {
449
+ cp.emit('error', spawnError);
450
+ cp.emit('exit', 1, null);
451
+ });
452
+
453
+ expect(result.error).toBe(spawnError);
454
+ expect(result.exitCode).toBe(1);
455
+ });
456
+
457
+ it('handles errors that do not fire the exit event', async () => {
458
+ const error = new Error('spawn abc ENOENT');
459
+ const { result } = await simulateExecution('touch cat.jpg', (cp) => {
460
+ cp.emit('error', error); // No exit event is fired.
461
+ });
462
+
463
+ expect(result.error).toBe(error);
464
+ expect(result.exitCode).toBe(1);
465
+ });
466
+ });
467
+
468
+ describe('Aborting Commands', () => {
469
+ describe.each([
470
+ {
471
+ platform: 'linux',
472
+ expectedSignal: 'SIGTERM',
473
+ expectedExit: { signal: 'SIGKILL' as const },
474
+ },
475
+ {
476
+ platform: 'win32',
477
+ expectedCommand: 'taskkill',
478
+ expectedExit: { code: 1 },
479
+ },
480
+ ])(
481
+ 'on $platform',
482
+ ({ platform, expectedSignal, expectedCommand, expectedExit }) => {
483
+ it('should abort a running process and set the aborted flag', async () => {
484
+ mockPlatform.mockReturnValue(platform);
485
+
486
+ const { result } = await simulateExecution(
487
+ 'sleep 10',
488
+ (cp, abortController) => {
489
+ abortController.abort();
490
+ if (expectedExit.signal)
491
+ cp.emit('exit', null, expectedExit.signal);
492
+ if (typeof expectedExit.code === 'number')
493
+ cp.emit('exit', expectedExit.code, null);
494
+ },
495
+ );
496
+
497
+ expect(result.aborted).toBe(true);
498
+
499
+ if (platform === 'linux') {
500
+ expect(mockProcessKill).toHaveBeenCalledWith(
501
+ -mockChildProcess.pid!,
502
+ expectedSignal,
503
+ );
504
+ } else {
505
+ expect(mockCpSpawn).toHaveBeenCalledWith(expectedCommand, [
506
+ '/pid',
507
+ String(mockChildProcess.pid),
508
+ '/f',
509
+ '/t',
510
+ ]);
511
+ }
512
+ });
513
+ },
514
+ );
515
+
516
+ it('should gracefully attempt SIGKILL on linux if SIGTERM fails', async () => {
517
+ mockPlatform.mockReturnValue('linux');
518
+ vi.useFakeTimers();
519
+
520
+ // Don't await the result inside the simulation block for this specific test.
521
+ // We need to control the timeline manually.
522
+ const abortController = new AbortController();
523
+ const handle = await ShellExecutionService.execute(
524
+ 'unresponsive_process',
525
+ '/test/dir',
526
+ onOutputEventMock,
527
+ abortController.signal,
528
+ true,
529
+ );
530
+
531
+ abortController.abort();
532
+
533
+ // Check the first kill signal
534
+ expect(mockProcessKill).toHaveBeenCalledWith(
535
+ -mockChildProcess.pid!,
536
+ 'SIGTERM',
537
+ );
538
+
539
+ // Now, advance time past the timeout
540
+ await vi.advanceTimersByTimeAsync(250);
541
+
542
+ // Check the second kill signal
543
+ expect(mockProcessKill).toHaveBeenCalledWith(
544
+ -mockChildProcess.pid!,
545
+ 'SIGKILL',
546
+ );
547
+
548
+ // Finally, simulate the process exiting and await the result
549
+ mockChildProcess.emit('exit', null, 'SIGKILL');
550
+ const result = await handle.result;
551
+
552
+ vi.useRealTimers();
553
+
554
+ expect(result.aborted).toBe(true);
555
+ expect(result.signal).toBe(9);
556
+ // The individual kill calls were already asserted above.
557
+ expect(mockProcessKill).toHaveBeenCalledTimes(2);
558
+ });
559
+ });
560
+
561
+ describe('Binary Output', () => {
562
+ it('should detect binary output and switch to progress events', async () => {
563
+ mockIsBinary.mockReturnValueOnce(true);
564
+ const binaryChunk1 = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
565
+ const binaryChunk2 = Buffer.from([0x0d, 0x0a, 0x1a, 0x0a]);
566
+
567
+ const { result } = await simulateExecution('cat image.png', (cp) => {
568
+ cp.stdout?.emit('data', binaryChunk1);
569
+ cp.stdout?.emit('data', binaryChunk2);
570
+ cp.emit('exit', 0, null);
571
+ });
572
+
573
+ expect(result.rawOutput).toEqual(
574
+ Buffer.concat([binaryChunk1, binaryChunk2]),
575
+ );
576
+ expect(onOutputEventMock).toHaveBeenCalledTimes(3);
577
+ expect(onOutputEventMock.mock.calls[0][0]).toEqual({
578
+ type: 'binary_detected',
579
+ });
580
+ expect(onOutputEventMock.mock.calls[1][0]).toEqual({
581
+ type: 'binary_progress',
582
+ bytesReceived: 4,
583
+ });
584
+ expect(onOutputEventMock.mock.calls[2][0]).toEqual({
585
+ type: 'binary_progress',
586
+ bytesReceived: 8,
587
+ });
588
+ });
589
+
590
+ it('should not emit data events after binary is detected', async () => {
591
+ mockIsBinary.mockImplementation((buffer) => buffer.includes(0x00));
592
+
593
+ await simulateExecution('cat mixed_file', (cp) => {
594
+ cp.stdout?.emit('data', Buffer.from('some text'));
595
+ cp.stdout?.emit('data', Buffer.from([0x00, 0x01, 0x02]));
596
+ cp.stdout?.emit('data', Buffer.from('more text'));
597
+ cp.emit('exit', 0, null);
598
+ });
599
+
600
+ const eventTypes = onOutputEventMock.mock.calls.map(
601
+ (call: [ShellOutputEvent]) => call[0].type,
602
+ );
603
+ expect(eventTypes).toEqual([
604
+ 'data',
605
+ 'binary_detected',
606
+ 'binary_progress',
607
+ 'binary_progress',
608
+ ]);
609
+ });
610
+ });
611
+
612
+ describe('Platform-Specific Behavior', () => {
613
+ it('should use cmd.exe on Windows', async () => {
614
+ mockPlatform.mockReturnValue('win32');
615
+ await simulateExecution('dir "foo bar"', (cp) =>
616
+ cp.emit('exit', 0, null),
617
+ );
618
+
619
+ expect(mockCpSpawn).toHaveBeenCalledWith(
620
+ 'dir "foo bar"',
621
+ [],
622
+ expect.objectContaining({
623
+ shell: true,
624
+ detached: false,
625
+ }),
626
+ );
627
+ });
628
+
629
+ it('should use bash and detached process group on Linux', async () => {
630
+ mockPlatform.mockReturnValue('linux');
631
+ await simulateExecution('ls "foo bar"', (cp) => cp.emit('exit', 0, null));
632
+
633
+ expect(mockCpSpawn).toHaveBeenCalledWith(
634
+ 'ls "foo bar"',
635
+ [],
636
+ expect.objectContaining({
637
+ shell: 'bash',
638
+ detached: true,
639
+ }),
640
+ );
641
+ });
642
+ });
643
+ });
644
+
645
+ describe('ShellExecutionService execution method selection', () => {
646
+ let onOutputEventMock: Mock<(event: ShellOutputEvent) => void>;
647
+ let mockPtyProcess: EventEmitter & {
648
+ pid: number;
649
+ kill: Mock;
650
+ onData: Mock;
651
+ onExit: Mock;
652
+ };
653
+ let mockChildProcess: EventEmitter & Partial<ChildProcess>;
654
+
655
+ beforeEach(() => {
656
+ vi.clearAllMocks();
657
+ onOutputEventMock = vi.fn();
658
+
659
+ // Mock for pty
660
+ mockPtyProcess = new EventEmitter() as EventEmitter & {
661
+ pid: number;
662
+ kill: Mock;
663
+ onData: Mock;
664
+ onExit: Mock;
665
+ };
666
+ mockPtyProcess.pid = 12345;
667
+ mockPtyProcess.kill = vi.fn();
668
+ mockPtyProcess.onData = vi.fn();
669
+ mockPtyProcess.onExit = vi.fn();
670
+ mockPtySpawn.mockReturnValue(mockPtyProcess);
671
+ mockGetPty.mockResolvedValue({
672
+ module: { spawn: mockPtySpawn },
673
+ name: 'mock-pty',
674
+ });
675
+
676
+ // Mock for child_process
677
+ mockChildProcess = new EventEmitter() as EventEmitter &
678
+ Partial<ChildProcess>;
679
+ mockChildProcess.stdout = new EventEmitter() as Readable;
680
+ mockChildProcess.stderr = new EventEmitter() as Readable;
681
+ mockChildProcess.kill = vi.fn();
682
+ Object.defineProperty(mockChildProcess, 'pid', {
683
+ value: 54321,
684
+ configurable: true,
685
+ });
686
+ mockCpSpawn.mockReturnValue(mockChildProcess);
687
+ });
688
+
689
+ it('should use node-pty when shouldUseNodePty is true and pty is available', async () => {
690
+ const abortController = new AbortController();
691
+ const handle = await ShellExecutionService.execute(
692
+ 'test command',
693
+ '/test/dir',
694
+ onOutputEventMock,
695
+ abortController.signal,
696
+ true, // shouldUseNodePty
697
+ );
698
+
699
+ // Simulate exit to allow promise to resolve
700
+ mockPtyProcess.onExit.mock.calls[0][0]({ exitCode: 0, signal: null });
701
+ const result = await handle.result;
702
+
703
+ expect(mockGetPty).toHaveBeenCalled();
704
+ expect(mockPtySpawn).toHaveBeenCalled();
705
+ expect(mockCpSpawn).not.toHaveBeenCalled();
706
+ expect(result.executionMethod).toBe('mock-pty');
707
+ });
708
+
709
+ it('should use child_process when shouldUseNodePty is false', async () => {
710
+ const abortController = new AbortController();
711
+ const handle = await ShellExecutionService.execute(
712
+ 'test command',
713
+ '/test/dir',
714
+ onOutputEventMock,
715
+ abortController.signal,
716
+ false, // shouldUseNodePty
717
+ );
718
+
719
+ // Simulate exit to allow promise to resolve
720
+ mockChildProcess.emit('exit', 0, null);
721
+ const result = await handle.result;
722
+
723
+ expect(mockGetPty).not.toHaveBeenCalled();
724
+ expect(mockPtySpawn).not.toHaveBeenCalled();
725
+ expect(mockCpSpawn).toHaveBeenCalled();
726
+ expect(result.executionMethod).toBe('child_process');
727
+ });
728
+
729
+ it('should fall back to child_process if pty is not available even if shouldUseNodePty is true', async () => {
730
+ mockGetPty.mockResolvedValue(null);
731
+
732
+ const abortController = new AbortController();
733
+ const handle = await ShellExecutionService.execute(
734
+ 'test command',
735
+ '/test/dir',
736
+ onOutputEventMock,
737
+ abortController.signal,
738
+ true, // shouldUseNodePty
739
+ );
740
+
741
+ // Simulate exit to allow promise to resolve
742
+ mockChildProcess.emit('exit', 0, null);
743
+ const result = await handle.result;
744
+
745
+ expect(mockGetPty).toHaveBeenCalled();
746
+ expect(mockPtySpawn).not.toHaveBeenCalled();
747
+ expect(mockCpSpawn).toHaveBeenCalled();
748
+ expect(result.executionMethod).toBe('child_process');
749
+ });
750
+ });
projects/ui/qwen-code/packages/core/src/services/shellExecutionService.ts ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { getPty, PtyImplementation } from '../utils/getPty.js';
8
+ import { spawn as cpSpawn } from 'child_process';
9
+ import { TextDecoder } from 'util';
10
+ import os from 'os';
11
+ import { getCachedEncodingForBuffer } from '../utils/systemEncoding.js';
12
+ import { isBinary } from '../utils/textUtils.js';
13
+ import pkg from '@xterm/headless';
14
+ import stripAnsi from 'strip-ansi';
15
+ const { Terminal } = pkg;
16
+
17
+ const SIGKILL_TIMEOUT_MS = 200;
18
+
19
+ // @ts-expect-error getFullText is not a public API.
20
+ const getFullText = (terminal: Terminal) => {
21
+ const buffer = terminal.buffer.active;
22
+ const lines: string[] = [];
23
+ for (let i = 0; i < buffer.length; i++) {
24
+ const line = buffer.getLine(i);
25
+ lines.push(line ? line.translateToString(true) : '');
26
+ }
27
+ return lines.join('\n').trim();
28
+ };
29
+
30
+ /** A structured result from a shell command execution. */
31
+ export interface ShellExecutionResult {
32
+ /** The raw, unprocessed output buffer. */
33
+ rawOutput: Buffer;
34
+ /** The combined, decoded output as a string. */
35
+ output: string;
36
+ /** The process exit code, or null if terminated by a signal. */
37
+ exitCode: number | null;
38
+ /** The signal that terminated the process, if any. */
39
+ signal: number | null;
40
+ /** An error object if the process failed to spawn. */
41
+ error: Error | null;
42
+ /** A boolean indicating if the command was aborted by the user. */
43
+ aborted: boolean;
44
+ /** The process ID of the spawned shell. */
45
+ pid: number | undefined;
46
+ /** The method used to execute the shell command. */
47
+ executionMethod: 'lydell-node-pty' | 'node-pty' | 'child_process' | 'none';
48
+ }
49
+
50
+ /** A handle for an ongoing shell execution. */
51
+ export interface ShellExecutionHandle {
52
+ /** The process ID of the spawned shell. */
53
+ pid: number | undefined;
54
+ /** A promise that resolves with the complete execution result. */
55
+ result: Promise<ShellExecutionResult>;
56
+ }
57
+
58
+ /**
59
+ * Describes a structured event emitted during shell command execution.
60
+ */
61
+ export type ShellOutputEvent =
62
+ | {
63
+ /** The event contains a chunk of output data. */
64
+ type: 'data';
65
+ /** The decoded string chunk. */
66
+ chunk: string;
67
+ }
68
+ | {
69
+ /** Signals that the output stream has been identified as binary. */
70
+ type: 'binary_detected';
71
+ }
72
+ | {
73
+ /** Provides progress updates for a binary stream. */
74
+ type: 'binary_progress';
75
+ /** The total number of bytes received so far. */
76
+ bytesReceived: number;
77
+ };
78
+
79
+ /**
80
+ * A centralized service for executing shell commands with robust process
81
+ * management, cross-platform compatibility, and streaming output capabilities.
82
+ *
83
+ */
84
+ export class ShellExecutionService {
85
+ /**
86
+ * Executes a shell command using `node-pty`, capturing all output and lifecycle events.
87
+ *
88
+ * @param commandToExecute The exact command string to run.
89
+ * @param cwd The working directory to execute the command in.
90
+ * @param onOutputEvent A callback for streaming structured events about the execution, including data chunks and status updates.
91
+ * @param abortSignal An AbortSignal to terminate the process and its children.
92
+ * @returns An object containing the process ID (pid) and a promise that
93
+ * resolves with the complete execution result.
94
+ */
95
+ static async execute(
96
+ commandToExecute: string,
97
+ cwd: string,
98
+ onOutputEvent: (event: ShellOutputEvent) => void,
99
+ abortSignal: AbortSignal,
100
+ shouldUseNodePty: boolean,
101
+ terminalColumns?: number,
102
+ terminalRows?: number,
103
+ ): Promise<ShellExecutionHandle> {
104
+ if (shouldUseNodePty) {
105
+ const ptyInfo = await getPty();
106
+ if (ptyInfo) {
107
+ try {
108
+ return this.executeWithPty(
109
+ commandToExecute,
110
+ cwd,
111
+ onOutputEvent,
112
+ abortSignal,
113
+ terminalColumns,
114
+ terminalRows,
115
+ ptyInfo,
116
+ );
117
+ } catch (_e) {
118
+ // Fallback to child_process
119
+ }
120
+ }
121
+ }
122
+
123
+ return this.childProcessFallback(
124
+ commandToExecute,
125
+ cwd,
126
+ onOutputEvent,
127
+ abortSignal,
128
+ );
129
+ }
130
+
131
+ private static childProcessFallback(
132
+ commandToExecute: string,
133
+ cwd: string,
134
+ onOutputEvent: (event: ShellOutputEvent) => void,
135
+ abortSignal: AbortSignal,
136
+ ): ShellExecutionHandle {
137
+ try {
138
+ const isWindows = os.platform() === 'win32';
139
+
140
+ const child = cpSpawn(commandToExecute, [], {
141
+ cwd,
142
+ stdio: ['ignore', 'pipe', 'pipe'],
143
+ shell: isWindows ? true : 'bash',
144
+ detached: !isWindows,
145
+ env: {
146
+ ...process.env,
147
+ QWEN_CODE: '1',
148
+ TERM: 'xterm-256color',
149
+ PAGER: 'cat',
150
+ },
151
+ });
152
+
153
+ const result = new Promise<ShellExecutionResult>((resolve) => {
154
+ let stdoutDecoder: TextDecoder | null = null;
155
+ let stderrDecoder: TextDecoder | null = null;
156
+
157
+ let stdout = '';
158
+ let stderr = '';
159
+ const outputChunks: Buffer[] = [];
160
+ let error: Error | null = null;
161
+ let exited = false;
162
+
163
+ let isStreamingRawContent = true;
164
+ const MAX_SNIFF_SIZE = 4096;
165
+ let sniffedBytes = 0;
166
+
167
+ const handleOutput = (data: Buffer, stream: 'stdout' | 'stderr') => {
168
+ if (!stdoutDecoder || !stderrDecoder) {
169
+ const encoding = getCachedEncodingForBuffer(data);
170
+ try {
171
+ stdoutDecoder = new TextDecoder(encoding);
172
+ stderrDecoder = new TextDecoder(encoding);
173
+ } catch {
174
+ stdoutDecoder = new TextDecoder('utf-8');
175
+ stderrDecoder = new TextDecoder('utf-8');
176
+ }
177
+ }
178
+
179
+ outputChunks.push(data);
180
+
181
+ if (isStreamingRawContent && sniffedBytes < MAX_SNIFF_SIZE) {
182
+ const sniffBuffer = Buffer.concat(outputChunks.slice(0, 20));
183
+ sniffedBytes = sniffBuffer.length;
184
+
185
+ if (isBinary(sniffBuffer)) {
186
+ isStreamingRawContent = false;
187
+ onOutputEvent({ type: 'binary_detected' });
188
+ }
189
+ }
190
+
191
+ const decoder = stream === 'stdout' ? stdoutDecoder : stderrDecoder;
192
+ const decodedChunk = decoder.decode(data, { stream: true });
193
+ const strippedChunk = stripAnsi(decodedChunk);
194
+
195
+ if (stream === 'stdout') {
196
+ stdout += strippedChunk;
197
+ } else {
198
+ stderr += strippedChunk;
199
+ }
200
+
201
+ if (isStreamingRawContent) {
202
+ onOutputEvent({ type: 'data', chunk: strippedChunk });
203
+ } else {
204
+ const totalBytes = outputChunks.reduce(
205
+ (sum, chunk) => sum + chunk.length,
206
+ 0,
207
+ );
208
+ onOutputEvent({
209
+ type: 'binary_progress',
210
+ bytesReceived: totalBytes,
211
+ });
212
+ }
213
+ };
214
+
215
+ const handleExit = (
216
+ code: number | null,
217
+ signal: NodeJS.Signals | null,
218
+ ) => {
219
+ const { finalBuffer } = cleanup();
220
+ // Ensure we don't add an extra newline if stdout already ends with one.
221
+ const separator = stdout.endsWith('\n') ? '' : '\n';
222
+ const combinedOutput =
223
+ stdout + (stderr ? (stdout ? separator : '') + stderr : '');
224
+
225
+ resolve({
226
+ rawOutput: finalBuffer,
227
+ output: combinedOutput.trim(),
228
+ exitCode: code,
229
+ signal: signal ? os.constants.signals[signal] : null,
230
+ error,
231
+ aborted: abortSignal.aborted,
232
+ pid: child.pid,
233
+ executionMethod: 'child_process',
234
+ });
235
+ };
236
+
237
+ child.stdout.on('data', (data) => handleOutput(data, 'stdout'));
238
+ child.stderr.on('data', (data) => handleOutput(data, 'stderr'));
239
+ child.on('error', (err) => {
240
+ error = err;
241
+ handleExit(1, null);
242
+ });
243
+
244
+ const abortHandler = async () => {
245
+ if (child.pid && !exited) {
246
+ if (isWindows) {
247
+ cpSpawn('taskkill', ['/pid', child.pid.toString(), '/f', '/t']);
248
+ } else {
249
+ try {
250
+ process.kill(-child.pid, 'SIGTERM');
251
+ await new Promise((res) => setTimeout(res, SIGKILL_TIMEOUT_MS));
252
+ if (!exited) {
253
+ process.kill(-child.pid, 'SIGKILL');
254
+ }
255
+ } catch (_e) {
256
+ if (!exited) child.kill('SIGKILL');
257
+ }
258
+ }
259
+ }
260
+ };
261
+
262
+ abortSignal.addEventListener('abort', abortHandler, { once: true });
263
+
264
+ child.on('exit', (code, signal) => {
265
+ handleExit(code, signal);
266
+ });
267
+
268
+ function cleanup() {
269
+ exited = true;
270
+ abortSignal.removeEventListener('abort', abortHandler);
271
+ if (stdoutDecoder) {
272
+ const remaining = stdoutDecoder.decode();
273
+ if (remaining) {
274
+ stdout += stripAnsi(remaining);
275
+ }
276
+ }
277
+ if (stderrDecoder) {
278
+ const remaining = stderrDecoder.decode();
279
+ if (remaining) {
280
+ stderr += stripAnsi(remaining);
281
+ }
282
+ }
283
+
284
+ const finalBuffer = Buffer.concat(outputChunks);
285
+
286
+ return { stdout, stderr, finalBuffer };
287
+ }
288
+ });
289
+
290
+ return { pid: child.pid, result };
291
+ } catch (e) {
292
+ const error = e as Error;
293
+ return {
294
+ pid: undefined,
295
+ result: Promise.resolve({
296
+ error,
297
+ rawOutput: Buffer.from(''),
298
+ output: '',
299
+ exitCode: 1,
300
+ signal: null,
301
+ aborted: false,
302
+ pid: undefined,
303
+ executionMethod: 'none',
304
+ }),
305
+ };
306
+ }
307
+ }
308
+
309
+ private static executeWithPty(
310
+ commandToExecute: string,
311
+ cwd: string,
312
+ onOutputEvent: (event: ShellOutputEvent) => void,
313
+ abortSignal: AbortSignal,
314
+ terminalColumns: number | undefined,
315
+ terminalRows: number | undefined,
316
+ ptyInfo: PtyImplementation | undefined,
317
+ ): ShellExecutionHandle {
318
+ try {
319
+ const cols = terminalColumns ?? 80;
320
+ const rows = terminalRows ?? 30;
321
+ const isWindows = os.platform() === 'win32';
322
+ const shell = isWindows ? 'cmd.exe' : 'bash';
323
+ const args = isWindows
324
+ ? ['/c', commandToExecute]
325
+ : ['-c', commandToExecute];
326
+
327
+ const ptyProcess = ptyInfo?.module.spawn(shell, args, {
328
+ cwd,
329
+ name: 'xterm-color',
330
+ cols,
331
+ rows,
332
+ env: {
333
+ ...process.env,
334
+ QWEN_CODE: '1',
335
+ TERM: 'xterm-256color',
336
+ PAGER: 'cat',
337
+ },
338
+ handleFlowControl: true,
339
+ });
340
+
341
+ const result = new Promise<ShellExecutionResult>((resolve) => {
342
+ const headlessTerminal = new Terminal({
343
+ allowProposedApi: true,
344
+ cols,
345
+ rows,
346
+ });
347
+ let processingChain = Promise.resolve();
348
+ let decoder: TextDecoder | null = null;
349
+ let output = '';
350
+ const outputChunks: Buffer[] = [];
351
+ const error: Error | null = null;
352
+ let exited = false;
353
+
354
+ let isStreamingRawContent = true;
355
+ const MAX_SNIFF_SIZE = 4096;
356
+ let sniffedBytes = 0;
357
+
358
+ const handleOutput = (data: Buffer) => {
359
+ processingChain = processingChain.then(
360
+ () =>
361
+ new Promise<void>((resolve) => {
362
+ if (!decoder) {
363
+ const encoding = getCachedEncodingForBuffer(data);
364
+ try {
365
+ decoder = new TextDecoder(encoding);
366
+ } catch {
367
+ decoder = new TextDecoder('utf-8');
368
+ }
369
+ }
370
+
371
+ outputChunks.push(data);
372
+
373
+ if (isStreamingRawContent && sniffedBytes < MAX_SNIFF_SIZE) {
374
+ const sniffBuffer = Buffer.concat(outputChunks.slice(0, 20));
375
+ sniffedBytes = sniffBuffer.length;
376
+
377
+ if (isBinary(sniffBuffer)) {
378
+ isStreamingRawContent = false;
379
+ onOutputEvent({ type: 'binary_detected' });
380
+ }
381
+ }
382
+
383
+ if (isStreamingRawContent) {
384
+ const decodedChunk = decoder.decode(data, { stream: true });
385
+ headlessTerminal.write(decodedChunk, () => {
386
+ const newStrippedOutput = getFullText(headlessTerminal);
387
+ output = newStrippedOutput;
388
+ onOutputEvent({ type: 'data', chunk: newStrippedOutput });
389
+ resolve();
390
+ });
391
+ } else {
392
+ const totalBytes = outputChunks.reduce(
393
+ (sum, chunk) => sum + chunk.length,
394
+ 0,
395
+ );
396
+ onOutputEvent({
397
+ type: 'binary_progress',
398
+ bytesReceived: totalBytes,
399
+ });
400
+ resolve();
401
+ }
402
+ }),
403
+ );
404
+ };
405
+
406
+ ptyProcess.onData((data: string) => {
407
+ const bufferData = Buffer.from(data, 'utf-8');
408
+ handleOutput(bufferData);
409
+ });
410
+
411
+ ptyProcess.onExit(
412
+ ({ exitCode, signal }: { exitCode: number; signal?: number }) => {
413
+ exited = true;
414
+ abortSignal.removeEventListener('abort', abortHandler);
415
+
416
+ processingChain.then(() => {
417
+ const finalBuffer = Buffer.concat(outputChunks);
418
+
419
+ resolve({
420
+ rawOutput: finalBuffer,
421
+ output,
422
+ exitCode,
423
+ signal: signal ?? null,
424
+ error,
425
+ aborted: abortSignal.aborted,
426
+ pid: ptyProcess.pid,
427
+ executionMethod: ptyInfo?.name ?? 'node-pty',
428
+ });
429
+ });
430
+ },
431
+ );
432
+
433
+ const abortHandler = async () => {
434
+ if (ptyProcess.pid && !exited) {
435
+ ptyProcess.kill('SIGHUP');
436
+ }
437
+ };
438
+
439
+ abortSignal.addEventListener('abort', abortHandler, { once: true });
440
+ });
441
+
442
+ return { pid: ptyProcess.pid, result };
443
+ } catch (e) {
444
+ const error = e as Error;
445
+ return {
446
+ pid: undefined,
447
+ result: Promise.resolve({
448
+ error,
449
+ rawOutput: Buffer.from(''),
450
+ output: '',
451
+ exitCode: 1,
452
+ signal: null,
453
+ aborted: false,
454
+ pid: undefined,
455
+ executionMethod: 'none',
456
+ }),
457
+ };
458
+ }
459
+ }
460
+ }
projects/ui/qwen-code/packages/core/src/telemetry/constants.ts ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ export const SERVICE_NAME = 'qwen-code';
8
+
9
+ export const EVENT_USER_PROMPT = 'qwen-code.user_prompt';
10
+ export const EVENT_TOOL_CALL = 'qwen-code.tool_call';
11
+ export const EVENT_API_REQUEST = 'qwen-code.api_request';
12
+ export const EVENT_API_ERROR = 'qwen-code.api_error';
13
+ export const EVENT_API_RESPONSE = 'qwen-code.api_response';
14
+ export const EVENT_CLI_CONFIG = 'qwen-code.config';
15
+ export const EVENT_FLASH_FALLBACK = 'qwen-code.flash_fallback';
16
+ export const EVENT_NEXT_SPEAKER_CHECK = 'qwen-code.next_speaker_check';
17
+ export const EVENT_SLASH_COMMAND = 'qwen-code.slash_command';
18
+ export const EVENT_IDE_CONNECTION = 'qwen-code.ide_connection';
19
+ export const EVENT_CHAT_COMPRESSION = 'qwen-code.chat_compression';
20
+ export const EVENT_INVALID_CHUNK = 'qwen-code.chat.invalid_chunk';
21
+ export const EVENT_CONTENT_RETRY = 'qwen-code.chat.content_retry';
22
+ export const EVENT_CONTENT_RETRY_FAILURE =
23
+ 'qwen-code.chat.content_retry_failure';
24
+
25
+ export const METRIC_TOOL_CALL_COUNT = 'qwen-code.tool.call.count';
26
+ export const METRIC_TOOL_CALL_LATENCY = 'qwen-code.tool.call.latency';
27
+ export const METRIC_API_REQUEST_COUNT = 'qwen-code.api.request.count';
28
+ export const METRIC_API_REQUEST_LATENCY = 'qwen-code.api.request.latency';
29
+ export const METRIC_TOKEN_USAGE = 'qwen-code.token.usage';
30
+ export const METRIC_SESSION_COUNT = 'qwen-code.session.count';
31
+ export const METRIC_FILE_OPERATION_COUNT = 'qwen-code.file.operation.count';
32
+ export const METRIC_INVALID_CHUNK_COUNT = 'qwen-code.chat.invalid_chunk.count';
33
+ export const METRIC_CONTENT_RETRY_COUNT = 'qwen-code.chat.content_retry.count';
34
+ export const METRIC_CONTENT_RETRY_FAILURE_COUNT =
35
+ 'qwen-code.chat.content_retry_failure.count';
projects/ui/qwen-code/packages/core/src/telemetry/file-exporters.ts ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'node:fs';
8
+ import { ExportResult, ExportResultCode } from '@opentelemetry/core';
9
+ import { ReadableSpan, SpanExporter } from '@opentelemetry/sdk-trace-base';
10
+ import { ReadableLogRecord, LogRecordExporter } from '@opentelemetry/sdk-logs';
11
+ import {
12
+ ResourceMetrics,
13
+ PushMetricExporter,
14
+ AggregationTemporality,
15
+ } from '@opentelemetry/sdk-metrics';
16
+
17
+ class FileExporter {
18
+ protected writeStream: fs.WriteStream;
19
+
20
+ constructor(filePath: string) {
21
+ this.writeStream = fs.createWriteStream(filePath, { flags: 'a' });
22
+ }
23
+
24
+ protected serialize(data: unknown): string {
25
+ return JSON.stringify(data, null, 2) + '\n';
26
+ }
27
+
28
+ shutdown(): Promise<void> {
29
+ return new Promise((resolve) => {
30
+ this.writeStream.end(resolve);
31
+ });
32
+ }
33
+ }
34
+
35
+ export class FileSpanExporter extends FileExporter implements SpanExporter {
36
+ export(
37
+ spans: ReadableSpan[],
38
+ resultCallback: (result: ExportResult) => void,
39
+ ): void {
40
+ const data = spans.map((span) => this.serialize(span)).join('');
41
+ this.writeStream.write(data, (err) => {
42
+ resultCallback({
43
+ code: err ? ExportResultCode.FAILED : ExportResultCode.SUCCESS,
44
+ error: err || undefined,
45
+ });
46
+ });
47
+ }
48
+ }
49
+
50
+ export class FileLogExporter extends FileExporter implements LogRecordExporter {
51
+ export(
52
+ logs: ReadableLogRecord[],
53
+ resultCallback: (result: ExportResult) => void,
54
+ ): void {
55
+ const data = logs.map((log) => this.serialize(log)).join('');
56
+ this.writeStream.write(data, (err) => {
57
+ resultCallback({
58
+ code: err ? ExportResultCode.FAILED : ExportResultCode.SUCCESS,
59
+ error: err || undefined,
60
+ });
61
+ });
62
+ }
63
+ }
64
+
65
+ export class FileMetricExporter
66
+ extends FileExporter
67
+ implements PushMetricExporter
68
+ {
69
+ export(
70
+ metrics: ResourceMetrics,
71
+ resultCallback: (result: ExportResult) => void,
72
+ ): void {
73
+ const data = this.serialize(metrics);
74
+ this.writeStream.write(data, (err) => {
75
+ resultCallback({
76
+ code: err ? ExportResultCode.FAILED : ExportResultCode.SUCCESS,
77
+ error: err || undefined,
78
+ });
79
+ });
80
+ }
81
+
82
+ getPreferredAggregationTemporality(): AggregationTemporality {
83
+ return AggregationTemporality.CUMULATIVE;
84
+ }
85
+
86
+ async forceFlush(): Promise<void> {
87
+ return Promise.resolve();
88
+ }
89
+ }
projects/ui/qwen-code/packages/core/src/telemetry/index.ts ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ export enum TelemetryTarget {
8
+ GCP = 'gcp',
9
+ LOCAL = 'local',
10
+ QWEN = 'qwen',
11
+ }
12
+
13
+ const DEFAULT_TELEMETRY_TARGET = TelemetryTarget.LOCAL;
14
+ const DEFAULT_OTLP_ENDPOINT = 'http://localhost:4317';
15
+
16
+ export { DEFAULT_TELEMETRY_TARGET, DEFAULT_OTLP_ENDPOINT };
17
+ export {
18
+ initializeTelemetry,
19
+ shutdownTelemetry,
20
+ isTelemetrySdkInitialized,
21
+ } from './sdk.js';
22
+ export {
23
+ logCliConfiguration,
24
+ logUserPrompt,
25
+ logToolCall,
26
+ logApiRequest,
27
+ logApiError,
28
+ logApiResponse,
29
+ logFlashFallback,
30
+ logSlashCommand,
31
+ logKittySequenceOverflow,
32
+ logChatCompression,
33
+ } from './loggers.js';
34
+ export {
35
+ StartSessionEvent,
36
+ EndSessionEvent,
37
+ UserPromptEvent,
38
+ ToolCallEvent,
39
+ ApiRequestEvent,
40
+ ApiErrorEvent,
41
+ ApiResponseEvent,
42
+ TelemetryEvent,
43
+ FlashFallbackEvent,
44
+ KittySequenceOverflowEvent,
45
+ SlashCommandEvent,
46
+ makeSlashCommandEvent,
47
+ SlashCommandStatus,
48
+ ChatCompressionEvent,
49
+ makeChatCompressionEvent,
50
+ } from './types.js';
51
+ export { SpanStatusCode, ValueType } from '@opentelemetry/api';
52
+ export { SemanticAttributes } from '@opentelemetry/semantic-conventions';
53
+ export * from './uiTelemetry.js';
projects/ui/qwen-code/packages/core/src/telemetry/integration.test.circular.ts ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * Integration test to verify circular reference handling with proxy agents
9
+ */
10
+
11
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
12
+ import { QwenLogger } from './qwen-logger/qwen-logger.js';
13
+ import { RumEvent } from './qwen-logger/event-types.js';
14
+ import { Config } from '../config/config.js';
15
+
16
+ describe('Circular Reference Integration Test', () => {
17
+ beforeEach(() => {
18
+ // Clear singleton instance before each test
19
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
20
+ (QwenLogger as any).instance = undefined;
21
+ });
22
+
23
+ afterEach(() => {
24
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
+ (QwenLogger as any).instance = undefined;
26
+ });
27
+
28
+ it('should handle HttpsProxyAgent-like circular references in qwen logging', () => {
29
+ // Create a mock config with proxy
30
+ const mockConfig = {
31
+ getTelemetryEnabled: () => true,
32
+ getUsageStatisticsEnabled: () => true,
33
+ getSessionId: () => 'test-session',
34
+ getModel: () => 'test-model',
35
+ getEmbeddingModel: () => 'test-embedding',
36
+ getDebugMode: () => false,
37
+ getProxy: () => 'http://proxy.example.com:8080',
38
+ } as unknown as Config;
39
+
40
+ // Simulate the structure that causes the circular reference error
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ const proxyAgentLike: any = {
43
+ sockets: {},
44
+ options: { proxy: 'http://proxy.example.com:8080' },
45
+ };
46
+
47
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
48
+ const socketLike: any = {
49
+ _httpMessage: {
50
+ agent: proxyAgentLike,
51
+ socket: null,
52
+ },
53
+ };
54
+
55
+ socketLike._httpMessage.socket = socketLike; // Create circular reference
56
+ proxyAgentLike.sockets['cloudcode-pa.googleapis.com:443'] = [socketLike];
57
+
58
+ // Create an event that would contain this circular structure
59
+ const problematicEvent: RumEvent = {
60
+ timestamp: Date.now(),
61
+ event_type: 'exception',
62
+ type: 'error',
63
+ name: 'api_error',
64
+ error: new Error('Network error'),
65
+ function_args: {
66
+ filePath: '/test/file.txt',
67
+ httpAgent: proxyAgentLike, // This would cause the circular reference
68
+ },
69
+ } as RumEvent;
70
+
71
+ // Test that QwenLogger can handle this
72
+ const logger = QwenLogger.getInstance(mockConfig);
73
+
74
+ expect(() => {
75
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
76
+ logger?.enqueueLogEvent(problematicEvent as any);
77
+ }).not.toThrow();
78
+ });
79
+
80
+ it('should handle event overflow without memory leaks', () => {
81
+ const mockConfig = {
82
+ getTelemetryEnabled: () => true,
83
+ getUsageStatisticsEnabled: () => true,
84
+ getSessionId: () => 'test-session',
85
+ getDebugMode: () => true,
86
+ } as unknown as Config;
87
+
88
+ const logger = QwenLogger.getInstance(mockConfig);
89
+
90
+ // Add more events than the maximum capacity
91
+ for (let i = 0; i < 1100; i++) {
92
+ logger?.enqueueLogEvent({
93
+ timestamp: Date.now(),
94
+ event_type: 'action',
95
+ type: 'test',
96
+ name: `overflow-test-${i}`,
97
+ });
98
+ }
99
+
100
+ // Logger should still be functional
101
+ expect(logger).toBeDefined();
102
+ expect(() => {
103
+ logger?.enqueueLogEvent({
104
+ timestamp: Date.now(),
105
+ event_type: 'action',
106
+ type: 'test',
107
+ name: 'final-test',
108
+ });
109
+ }).not.toThrow();
110
+ });
111
+ });