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

Add files using upload-large-folder tool

Browse files
projects/ui/qwen-code/packages/core/src/telemetry/loggers.test.circular.ts ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /**
8
+ * Test to verify circular reference handling in telemetry logging
9
+ */
10
+
11
+ import { describe, it, expect } from 'vitest';
12
+ import { logToolCall } from './loggers.js';
13
+ import { ToolCallEvent } from './types.js';
14
+ import { Config } from '../config/config.js';
15
+ import { CompletedToolCall } from '../core/coreToolScheduler.js';
16
+ import { ToolCallRequestInfo, ToolCallResponseInfo } from '../core/turn.js';
17
+ import { MockTool } from '../test-utils/tools.js';
18
+
19
+ describe('Circular Reference Handling', () => {
20
+ it('should handle circular references in tool function arguments', () => {
21
+ // Create a mock config
22
+ const mockConfig = {
23
+ getTelemetryEnabled: () => true,
24
+ getUsageStatisticsEnabled: () => true,
25
+ getSessionId: () => 'test-session',
26
+ getModel: () => 'test-model',
27
+ getEmbeddingModel: () => 'test-embedding',
28
+ getDebugMode: () => false,
29
+ } as unknown as Config;
30
+
31
+ // Create an object with circular references (similar to HttpsProxyAgent)
32
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
33
+ const circularObject: any = {
34
+ sockets: {},
35
+ agent: null,
36
+ };
37
+ circularObject.agent = circularObject; // Create circular reference
38
+ circularObject.sockets['test-host'] = [
39
+ { _httpMessage: { agent: circularObject } },
40
+ ];
41
+
42
+ // Create a mock CompletedToolCall with circular references in function_args
43
+ const mockRequest: ToolCallRequestInfo = {
44
+ callId: 'test-call-id',
45
+ name: 'ReadFile',
46
+ args: circularObject, // This would cause the original error
47
+ isClientInitiated: false,
48
+ prompt_id: 'test-prompt-id',
49
+ };
50
+
51
+ const mockResponse: ToolCallResponseInfo = {
52
+ callId: 'test-call-id',
53
+ responseParts: [{ text: 'test result' }],
54
+ resultDisplay: undefined,
55
+ error: undefined, // undefined means success
56
+ errorType: undefined,
57
+ };
58
+
59
+ const tool = new MockTool('mock-tool');
60
+ const mockCompletedToolCall: CompletedToolCall = {
61
+ status: 'success',
62
+ request: mockRequest,
63
+ response: mockResponse,
64
+ tool,
65
+ invocation: tool.build({}),
66
+ durationMs: 100,
67
+ };
68
+
69
+ // Create a tool call event with circular references in function_args
70
+ const event = new ToolCallEvent(mockCompletedToolCall);
71
+
72
+ // This should not throw an error
73
+ expect(() => {
74
+ logToolCall(mockConfig, event);
75
+ }).not.toThrow();
76
+ });
77
+
78
+ it('should handle normal objects without circular references', () => {
79
+ const mockConfig = {
80
+ getTelemetryEnabled: () => true,
81
+ getUsageStatisticsEnabled: () => true,
82
+ getSessionId: () => 'test-session',
83
+ getModel: () => 'test-model',
84
+ getEmbeddingModel: () => 'test-embedding',
85
+ getDebugMode: () => false,
86
+ } as unknown as Config;
87
+
88
+ const normalObject = {
89
+ filePath: '/test/path',
90
+ options: { encoding: 'utf8' },
91
+ };
92
+
93
+ const mockRequest: ToolCallRequestInfo = {
94
+ callId: 'test-call-id',
95
+ name: 'ReadFile',
96
+ args: normalObject,
97
+ isClientInitiated: false,
98
+ prompt_id: 'test-prompt-id',
99
+ };
100
+
101
+ const mockResponse: ToolCallResponseInfo = {
102
+ callId: 'test-call-id',
103
+ responseParts: [{ text: 'test result' }],
104
+ resultDisplay: undefined,
105
+ error: undefined, // undefined means success
106
+ errorType: undefined,
107
+ };
108
+
109
+ const tool = new MockTool('mock-tool');
110
+ const mockCompletedToolCall: CompletedToolCall = {
111
+ status: 'success',
112
+ request: mockRequest,
113
+ response: mockResponse,
114
+ tool,
115
+ invocation: tool.build({}),
116
+ durationMs: 100,
117
+ };
118
+
119
+ const event = new ToolCallEvent(mockCompletedToolCall);
120
+
121
+ expect(() => {
122
+ logToolCall(mockConfig, event);
123
+ }).not.toThrow();
124
+ });
125
+ });
projects/ui/qwen-code/packages/core/src/telemetry/loggers.test.ts ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ AnyToolInvocation,
9
+ AuthType,
10
+ CompletedToolCall,
11
+ ContentGeneratorConfig,
12
+ EditTool,
13
+ ErroredToolCall,
14
+ GeminiClient,
15
+ ToolConfirmationOutcome,
16
+ ToolErrorType,
17
+ ToolRegistry,
18
+ } from '../index.js';
19
+ import { logs } from '@opentelemetry/api-logs';
20
+ import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
21
+ import { Config } from '../config/config.js';
22
+ import {
23
+ EVENT_API_REQUEST,
24
+ EVENT_API_RESPONSE,
25
+ EVENT_CLI_CONFIG,
26
+ EVENT_TOOL_CALL,
27
+ EVENT_USER_PROMPT,
28
+ EVENT_FLASH_FALLBACK,
29
+ } from './constants.js';
30
+ import {
31
+ logApiRequest,
32
+ logApiResponse,
33
+ logCliConfiguration,
34
+ logUserPrompt,
35
+ logToolCall,
36
+ logFlashFallback,
37
+ logChatCompression,
38
+ } from './loggers.js';
39
+ import { ToolCallDecision } from './tool-call-decision.js';
40
+ import {
41
+ ApiRequestEvent,
42
+ ApiResponseEvent,
43
+ StartSessionEvent,
44
+ ToolCallEvent,
45
+ UserPromptEvent,
46
+ FlashFallbackEvent,
47
+ makeChatCompressionEvent,
48
+ } from './types.js';
49
+ import * as metrics from './metrics.js';
50
+ import * as sdk from './sdk.js';
51
+ import { vi, describe, beforeEach, it, expect } from 'vitest';
52
+ import { GenerateContentResponseUsageMetadata } from '@google/genai';
53
+ import * as uiTelemetry from './uiTelemetry.js';
54
+ import { makeFakeConfig } from '../test-utils/config.js';
55
+ import { QwenLogger } from './qwen-logger/qwen-logger.js';
56
+
57
+ describe('loggers', () => {
58
+ const mockLogger = {
59
+ emit: vi.fn(),
60
+ };
61
+ const mockUiEvent = {
62
+ addEvent: vi.fn(),
63
+ };
64
+
65
+ beforeEach(() => {
66
+ vi.spyOn(sdk, 'isTelemetrySdkInitialized').mockReturnValue(true);
67
+ vi.spyOn(logs, 'getLogger').mockReturnValue(mockLogger);
68
+ vi.spyOn(uiTelemetry.uiTelemetryService, 'addEvent').mockImplementation(
69
+ mockUiEvent.addEvent,
70
+ );
71
+ vi.useFakeTimers();
72
+ vi.setSystemTime(new Date('2025-01-01T00:00:00.000Z'));
73
+ });
74
+
75
+ describe('logChatCompression', () => {
76
+ beforeEach(() => {
77
+ vi.spyOn(metrics, 'recordChatCompressionMetrics');
78
+ vi.spyOn(QwenLogger.prototype, 'logChatCompressionEvent');
79
+ });
80
+
81
+ it('logs the chat compression event to QwenLogger', () => {
82
+ const mockConfig = makeFakeConfig();
83
+
84
+ const event = makeChatCompressionEvent({
85
+ tokens_before: 9001,
86
+ tokens_after: 9000,
87
+ });
88
+
89
+ logChatCompression(mockConfig, event);
90
+
91
+ expect(QwenLogger.prototype.logChatCompressionEvent).toHaveBeenCalledWith(
92
+ event,
93
+ );
94
+ });
95
+
96
+ it('records the chat compression event to OTEL', () => {
97
+ const mockConfig = makeFakeConfig();
98
+
99
+ logChatCompression(
100
+ mockConfig,
101
+ makeChatCompressionEvent({
102
+ tokens_before: 9001,
103
+ tokens_after: 9000,
104
+ }),
105
+ );
106
+
107
+ expect(metrics.recordChatCompressionMetrics).toHaveBeenCalledWith(
108
+ mockConfig,
109
+ { tokens_before: 9001, tokens_after: 9000 },
110
+ );
111
+ });
112
+ });
113
+
114
+ describe('logCliConfiguration', () => {
115
+ it('should log the cli configuration', () => {
116
+ const mockConfig = {
117
+ getSessionId: () => 'test-session-id',
118
+ getModel: () => 'test-model',
119
+ getEmbeddingModel: () => 'test-embedding-model',
120
+ getSandbox: () => true,
121
+ getCoreTools: () => ['ls', 'read-file'],
122
+ getApprovalMode: () => 'default',
123
+ getContentGeneratorConfig: () => ({
124
+ model: 'test-model',
125
+ apiKey: 'test-api-key',
126
+ authType: AuthType.USE_VERTEX_AI,
127
+ }),
128
+ getTelemetryEnabled: () => true,
129
+ getUsageStatisticsEnabled: () => true,
130
+ getTelemetryLogPromptsEnabled: () => true,
131
+ getFileFilteringRespectGitIgnore: () => true,
132
+ getFileFilteringAllowBuildArtifacts: () => false,
133
+ getDebugMode: () => true,
134
+ getMcpServers: () => ({
135
+ 'test-server': {
136
+ command: 'test-command',
137
+ },
138
+ }),
139
+ getQuestion: () => 'test-question',
140
+ getTargetDir: () => 'target-dir',
141
+ getProxy: () => 'http://test.proxy.com:8080',
142
+ } as unknown as Config;
143
+
144
+ const startSessionEvent = new StartSessionEvent(mockConfig);
145
+ logCliConfiguration(mockConfig, startSessionEvent);
146
+
147
+ expect(mockLogger.emit).toHaveBeenCalledWith({
148
+ body: 'CLI configuration loaded.',
149
+ attributes: {
150
+ 'session.id': 'test-session-id',
151
+ 'event.name': EVENT_CLI_CONFIG,
152
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
153
+ model: 'test-model',
154
+ embedding_model: 'test-embedding-model',
155
+ sandbox_enabled: true,
156
+ core_tools_enabled: 'ls,read-file',
157
+ approval_mode: 'default',
158
+ api_key_enabled: true,
159
+ vertex_ai_enabled: true,
160
+ log_user_prompts_enabled: true,
161
+ file_filtering_respect_git_ignore: true,
162
+ debug_mode: true,
163
+ mcp_servers: 'test-server',
164
+ },
165
+ });
166
+ });
167
+ });
168
+
169
+ describe('logUserPrompt', () => {
170
+ const mockConfig = {
171
+ getSessionId: () => 'test-session-id',
172
+ getTelemetryEnabled: () => true,
173
+ getTelemetryLogPromptsEnabled: () => true,
174
+ getUsageStatisticsEnabled: () => true,
175
+ } as unknown as Config;
176
+
177
+ it('should log a user prompt', () => {
178
+ const event = new UserPromptEvent(
179
+ 11,
180
+ 'prompt-id-8',
181
+ AuthType.USE_VERTEX_AI,
182
+ 'test-prompt',
183
+ );
184
+
185
+ logUserPrompt(mockConfig, event);
186
+
187
+ expect(mockLogger.emit).toHaveBeenCalledWith({
188
+ body: 'User prompt. Length: 11.',
189
+ attributes: {
190
+ 'session.id': 'test-session-id',
191
+ 'event.name': EVENT_USER_PROMPT,
192
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
193
+ prompt_length: 11,
194
+ prompt: 'test-prompt',
195
+ },
196
+ });
197
+ });
198
+
199
+ it('should not log prompt if disabled', () => {
200
+ const mockConfig = {
201
+ getSessionId: () => 'test-session-id',
202
+ getTelemetryEnabled: () => true,
203
+ getTelemetryLogPromptsEnabled: () => false,
204
+ getTargetDir: () => 'target-dir',
205
+ getUsageStatisticsEnabled: () => true,
206
+ } as unknown as Config;
207
+ const event = new UserPromptEvent(
208
+ 11,
209
+ 'test-prompt',
210
+ AuthType.CLOUD_SHELL,
211
+ );
212
+
213
+ logUserPrompt(mockConfig, event);
214
+
215
+ expect(mockLogger.emit).toHaveBeenCalledWith({
216
+ body: 'User prompt. Length: 11.',
217
+ attributes: {
218
+ 'session.id': 'test-session-id',
219
+ 'event.name': EVENT_USER_PROMPT,
220
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
221
+ prompt_length: 11,
222
+ },
223
+ });
224
+ });
225
+ });
226
+
227
+ describe('logApiResponse', () => {
228
+ const mockConfig = {
229
+ getSessionId: () => 'test-session-id',
230
+ getTargetDir: () => 'target-dir',
231
+ getUsageStatisticsEnabled: () => true,
232
+ getTelemetryEnabled: () => true,
233
+ getTelemetryLogPromptsEnabled: () => true,
234
+ } as Config;
235
+
236
+ const mockMetrics = {
237
+ recordApiResponseMetrics: vi.fn(),
238
+ recordTokenUsageMetrics: vi.fn(),
239
+ };
240
+
241
+ beforeEach(() => {
242
+ vi.spyOn(metrics, 'recordApiResponseMetrics').mockImplementation(
243
+ mockMetrics.recordApiResponseMetrics,
244
+ );
245
+ vi.spyOn(metrics, 'recordTokenUsageMetrics').mockImplementation(
246
+ mockMetrics.recordTokenUsageMetrics,
247
+ );
248
+ });
249
+
250
+ it('should log an API response with all fields', () => {
251
+ const usageData: GenerateContentResponseUsageMetadata = {
252
+ promptTokenCount: 17,
253
+ candidatesTokenCount: 50,
254
+ cachedContentTokenCount: 10,
255
+ thoughtsTokenCount: 5,
256
+ toolUsePromptTokenCount: 2,
257
+ };
258
+ const event = new ApiResponseEvent(
259
+ 'test-response-id',
260
+ 'test-model',
261
+ 100,
262
+ 'prompt-id-1',
263
+ AuthType.LOGIN_WITH_GOOGLE,
264
+ usageData,
265
+ 'test-response',
266
+ );
267
+
268
+ logApiResponse(mockConfig, event);
269
+
270
+ expect(mockLogger.emit).toHaveBeenCalledWith({
271
+ body: 'API response from test-model. Status: 200. Duration: 100ms.',
272
+ attributes: {
273
+ 'session.id': 'test-session-id',
274
+ 'event.name': EVENT_API_RESPONSE,
275
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
276
+ [SemanticAttributes.HTTP_STATUS_CODE]: 200,
277
+ response_id: 'test-response-id',
278
+ model: 'test-model',
279
+ status_code: 200,
280
+ duration_ms: 100,
281
+ input_token_count: 17,
282
+ output_token_count: 50,
283
+ cached_content_token_count: 10,
284
+ thoughts_token_count: 5,
285
+ tool_token_count: 2,
286
+ total_token_count: 0,
287
+ response_text: 'test-response',
288
+ prompt_id: 'prompt-id-1',
289
+ auth_type: 'oauth-personal',
290
+ },
291
+ });
292
+
293
+ expect(mockMetrics.recordApiResponseMetrics).toHaveBeenCalledWith(
294
+ mockConfig,
295
+ 'test-model',
296
+ 100,
297
+ 200,
298
+ undefined,
299
+ );
300
+
301
+ expect(mockMetrics.recordTokenUsageMetrics).toHaveBeenCalledWith(
302
+ mockConfig,
303
+ 'test-model',
304
+ 50,
305
+ 'output',
306
+ );
307
+
308
+ expect(mockUiEvent.addEvent).toHaveBeenCalledWith({
309
+ ...event,
310
+ 'event.name': EVENT_API_RESPONSE,
311
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
312
+ });
313
+ });
314
+
315
+ it('should log an API response with an error', () => {
316
+ const usageData: GenerateContentResponseUsageMetadata = {
317
+ promptTokenCount: 17,
318
+ candidatesTokenCount: 50,
319
+ cachedContentTokenCount: 10,
320
+ thoughtsTokenCount: 5,
321
+ toolUsePromptTokenCount: 2,
322
+ };
323
+ const event = new ApiResponseEvent(
324
+ 'test-response-id-2',
325
+ 'test-model',
326
+ 100,
327
+ 'prompt-id-1',
328
+ AuthType.USE_GEMINI,
329
+ usageData,
330
+ 'test-response',
331
+ 'test-error',
332
+ );
333
+
334
+ logApiResponse(mockConfig, event);
335
+
336
+ expect(mockLogger.emit).toHaveBeenCalledWith({
337
+ body: 'API response from test-model. Status: 200. Duration: 100ms.',
338
+ attributes: {
339
+ 'session.id': 'test-session-id',
340
+ ...event,
341
+ 'event.name': EVENT_API_RESPONSE,
342
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
343
+ 'error.message': 'test-error',
344
+ },
345
+ });
346
+
347
+ expect(mockUiEvent.addEvent).toHaveBeenCalledWith({
348
+ ...event,
349
+ 'event.name': EVENT_API_RESPONSE,
350
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
351
+ });
352
+ });
353
+ });
354
+
355
+ describe('logApiRequest', () => {
356
+ const mockConfig = {
357
+ getSessionId: () => 'test-session-id',
358
+ getTargetDir: () => 'target-dir',
359
+ getUsageStatisticsEnabled: () => true,
360
+ getTelemetryEnabled: () => true,
361
+ getTelemetryLogPromptsEnabled: () => true,
362
+ } as Config;
363
+
364
+ it('should log an API request with request_text', () => {
365
+ const event = new ApiRequestEvent(
366
+ 'test-model',
367
+ 'prompt-id-7',
368
+ 'This is a test request',
369
+ );
370
+
371
+ logApiRequest(mockConfig, event);
372
+
373
+ expect(mockLogger.emit).toHaveBeenCalledWith({
374
+ body: 'API request to test-model.',
375
+ attributes: {
376
+ 'session.id': 'test-session-id',
377
+ 'event.name': EVENT_API_REQUEST,
378
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
379
+ model: 'test-model',
380
+ request_text: 'This is a test request',
381
+ prompt_id: 'prompt-id-7',
382
+ },
383
+ });
384
+ });
385
+
386
+ it('should log an API request without request_text', () => {
387
+ const event = new ApiRequestEvent('test-model', 'prompt-id-6');
388
+
389
+ logApiRequest(mockConfig, event);
390
+
391
+ expect(mockLogger.emit).toHaveBeenCalledWith({
392
+ body: 'API request to test-model.',
393
+ attributes: {
394
+ 'session.id': 'test-session-id',
395
+ 'event.name': EVENT_API_REQUEST,
396
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
397
+ model: 'test-model',
398
+ prompt_id: 'prompt-id-6',
399
+ },
400
+ });
401
+ });
402
+ });
403
+
404
+ describe('logFlashFallback', () => {
405
+ const mockConfig = {
406
+ getSessionId: () => 'test-session-id',
407
+ getUsageStatisticsEnabled: () => true,
408
+ } as unknown as Config;
409
+
410
+ it('should log flash fallback event', () => {
411
+ const event = new FlashFallbackEvent(AuthType.USE_VERTEX_AI);
412
+
413
+ logFlashFallback(mockConfig, event);
414
+
415
+ expect(mockLogger.emit).toHaveBeenCalledWith({
416
+ body: 'Switching to flash as Fallback.',
417
+ attributes: {
418
+ 'session.id': 'test-session-id',
419
+ 'event.name': EVENT_FLASH_FALLBACK,
420
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
421
+ auth_type: 'vertex-ai',
422
+ },
423
+ });
424
+ });
425
+ });
426
+
427
+ describe('logToolCall', () => {
428
+ const cfg1 = {
429
+ getSessionId: () => 'test-session-id',
430
+ getTargetDir: () => 'target-dir',
431
+ getGeminiClient: () => mockGeminiClient,
432
+ } as Config;
433
+ const cfg2 = {
434
+ getSessionId: () => 'test-session-id',
435
+ getTargetDir: () => 'target-dir',
436
+ getProxy: () => 'http://test.proxy.com:8080',
437
+ getContentGeneratorConfig: () =>
438
+ ({ model: 'test-model' }) as ContentGeneratorConfig,
439
+ getModel: () => 'test-model',
440
+ getEmbeddingModel: () => 'test-embedding-model',
441
+ getWorkingDir: () => 'test-working-dir',
442
+ getSandbox: () => true,
443
+ getCoreTools: () => ['ls', 'read-file'],
444
+ getApprovalMode: () => 'default',
445
+ getTelemetryLogPromptsEnabled: () => true,
446
+ getFileFilteringRespectGitIgnore: () => true,
447
+ getFileFilteringAllowBuildArtifacts: () => false,
448
+ getDebugMode: () => true,
449
+ getMcpServers: () => ({
450
+ 'test-server': {
451
+ command: 'test-command',
452
+ },
453
+ }),
454
+ getQuestion: () => 'test-question',
455
+ getToolRegistry: () => new ToolRegistry(cfg1),
456
+ getFullContext: () => false,
457
+ getUserMemory: () => 'user-memory',
458
+ } as unknown as Config;
459
+
460
+ const mockGeminiClient = new GeminiClient(cfg2);
461
+ const mockConfig = {
462
+ getSessionId: () => 'test-session-id',
463
+ getTargetDir: () => 'target-dir',
464
+ getGeminiClient: () => mockGeminiClient,
465
+ getUsageStatisticsEnabled: () => true,
466
+ getTelemetryEnabled: () => true,
467
+ getTelemetryLogPromptsEnabled: () => true,
468
+ } as Config;
469
+
470
+ const mockMetrics = {
471
+ recordToolCallMetrics: vi.fn(),
472
+ };
473
+
474
+ beforeEach(() => {
475
+ vi.spyOn(metrics, 'recordToolCallMetrics').mockImplementation(
476
+ mockMetrics.recordToolCallMetrics,
477
+ );
478
+ mockLogger.emit.mockReset();
479
+ });
480
+
481
+ it('should log a tool call with all fields', () => {
482
+ const tool = new EditTool(mockConfig);
483
+ const call: CompletedToolCall = {
484
+ status: 'success',
485
+ request: {
486
+ name: 'test-function',
487
+ args: {
488
+ arg1: 'value1',
489
+ arg2: 2,
490
+ },
491
+ callId: 'test-call-id',
492
+ isClientInitiated: true,
493
+ prompt_id: 'prompt-id-1',
494
+ },
495
+ response: {
496
+ callId: 'test-call-id',
497
+ responseParts: 'test-response',
498
+ resultDisplay: undefined,
499
+ error: undefined,
500
+ errorType: undefined,
501
+ },
502
+ tool,
503
+ invocation: {} as AnyToolInvocation,
504
+ durationMs: 100,
505
+ outcome: ToolConfirmationOutcome.ProceedOnce,
506
+ };
507
+ const event = new ToolCallEvent(call);
508
+
509
+ logToolCall(mockConfig, event);
510
+
511
+ expect(mockLogger.emit).toHaveBeenCalledWith({
512
+ body: 'Tool call: test-function. Decision: accept. Success: true. Duration: 100ms.',
513
+ attributes: {
514
+ 'session.id': 'test-session-id',
515
+ 'event.name': EVENT_TOOL_CALL,
516
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
517
+ function_name: 'test-function',
518
+ function_args: JSON.stringify(
519
+ {
520
+ arg1: 'value1',
521
+ arg2: 2,
522
+ },
523
+ null,
524
+ 2,
525
+ ),
526
+ duration_ms: 100,
527
+ success: true,
528
+ decision: ToolCallDecision.ACCEPT,
529
+ prompt_id: 'prompt-id-1',
530
+ tool_type: 'native',
531
+ },
532
+ });
533
+
534
+ expect(mockMetrics.recordToolCallMetrics).toHaveBeenCalledWith(
535
+ mockConfig,
536
+ 'test-function',
537
+ 100,
538
+ true,
539
+ ToolCallDecision.ACCEPT,
540
+ 'native',
541
+ );
542
+
543
+ expect(mockUiEvent.addEvent).toHaveBeenCalledWith({
544
+ ...event,
545
+ 'event.name': EVENT_TOOL_CALL,
546
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
547
+ });
548
+ });
549
+ it('should log a tool call with a reject decision', () => {
550
+ const call: ErroredToolCall = {
551
+ status: 'error',
552
+ request: {
553
+ name: 'test-function',
554
+ args: {
555
+ arg1: 'value1',
556
+ arg2: 2,
557
+ },
558
+ callId: 'test-call-id',
559
+ isClientInitiated: true,
560
+ prompt_id: 'prompt-id-2',
561
+ },
562
+ response: {
563
+ callId: 'test-call-id',
564
+ responseParts: 'test-response',
565
+ resultDisplay: undefined,
566
+ error: undefined,
567
+ errorType: undefined,
568
+ },
569
+ durationMs: 100,
570
+ outcome: ToolConfirmationOutcome.Cancel,
571
+ };
572
+ const event = new ToolCallEvent(call);
573
+
574
+ logToolCall(mockConfig, event);
575
+
576
+ expect(mockLogger.emit).toHaveBeenCalledWith({
577
+ body: 'Tool call: test-function. Decision: reject. Success: false. Duration: 100ms.',
578
+ attributes: {
579
+ 'session.id': 'test-session-id',
580
+ 'event.name': EVENT_TOOL_CALL,
581
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
582
+ function_name: 'test-function',
583
+ function_args: JSON.stringify(
584
+ {
585
+ arg1: 'value1',
586
+ arg2: 2,
587
+ },
588
+ null,
589
+ 2,
590
+ ),
591
+ duration_ms: 100,
592
+ success: false,
593
+ decision: ToolCallDecision.REJECT,
594
+ prompt_id: 'prompt-id-2',
595
+ tool_type: 'native',
596
+ },
597
+ });
598
+
599
+ expect(mockMetrics.recordToolCallMetrics).toHaveBeenCalledWith(
600
+ mockConfig,
601
+ 'test-function',
602
+ 100,
603
+ false,
604
+ ToolCallDecision.REJECT,
605
+ 'native',
606
+ );
607
+
608
+ expect(mockUiEvent.addEvent).toHaveBeenCalledWith({
609
+ ...event,
610
+ 'event.name': EVENT_TOOL_CALL,
611
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
612
+ });
613
+ });
614
+
615
+ it('should log a tool call with a modify decision', () => {
616
+ const call: CompletedToolCall = {
617
+ status: 'success',
618
+ request: {
619
+ name: 'test-function',
620
+ args: {
621
+ arg1: 'value1',
622
+ arg2: 2,
623
+ },
624
+ callId: 'test-call-id',
625
+ isClientInitiated: true,
626
+ prompt_id: 'prompt-id-3',
627
+ },
628
+ response: {
629
+ callId: 'test-call-id',
630
+ responseParts: 'test-response',
631
+ resultDisplay: undefined,
632
+ error: undefined,
633
+ errorType: undefined,
634
+ },
635
+ outcome: ToolConfirmationOutcome.ModifyWithEditor,
636
+ tool: new EditTool(mockConfig),
637
+ invocation: {} as AnyToolInvocation,
638
+ durationMs: 100,
639
+ };
640
+ const event = new ToolCallEvent(call);
641
+
642
+ logToolCall(mockConfig, event);
643
+
644
+ expect(mockLogger.emit).toHaveBeenCalledWith({
645
+ body: 'Tool call: test-function. Decision: modify. Success: true. Duration: 100ms.',
646
+ attributes: {
647
+ 'session.id': 'test-session-id',
648
+ 'event.name': EVENT_TOOL_CALL,
649
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
650
+ function_name: 'test-function',
651
+ function_args: JSON.stringify(
652
+ {
653
+ arg1: 'value1',
654
+ arg2: 2,
655
+ },
656
+ null,
657
+ 2,
658
+ ),
659
+ duration_ms: 100,
660
+ success: true,
661
+ decision: ToolCallDecision.MODIFY,
662
+ prompt_id: 'prompt-id-3',
663
+ tool_type: 'native',
664
+ },
665
+ });
666
+
667
+ expect(mockMetrics.recordToolCallMetrics).toHaveBeenCalledWith(
668
+ mockConfig,
669
+ 'test-function',
670
+ 100,
671
+ true,
672
+ ToolCallDecision.MODIFY,
673
+ 'native',
674
+ );
675
+
676
+ expect(mockUiEvent.addEvent).toHaveBeenCalledWith({
677
+ ...event,
678
+ 'event.name': EVENT_TOOL_CALL,
679
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
680
+ });
681
+ });
682
+
683
+ it('should log a tool call without a decision', () => {
684
+ const call: CompletedToolCall = {
685
+ status: 'success',
686
+ request: {
687
+ name: 'test-function',
688
+ args: {
689
+ arg1: 'value1',
690
+ arg2: 2,
691
+ },
692
+ callId: 'test-call-id',
693
+ isClientInitiated: true,
694
+ prompt_id: 'prompt-id-4',
695
+ },
696
+ response: {
697
+ callId: 'test-call-id',
698
+ responseParts: 'test-response',
699
+ resultDisplay: undefined,
700
+ error: undefined,
701
+ errorType: undefined,
702
+ },
703
+ tool: new EditTool(mockConfig),
704
+ invocation: {} as AnyToolInvocation,
705
+ durationMs: 100,
706
+ };
707
+ const event = new ToolCallEvent(call);
708
+
709
+ logToolCall(mockConfig, event);
710
+
711
+ expect(mockLogger.emit).toHaveBeenCalledWith({
712
+ body: 'Tool call: test-function. Success: true. Duration: 100ms.',
713
+ attributes: {
714
+ 'session.id': 'test-session-id',
715
+ 'event.name': EVENT_TOOL_CALL,
716
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
717
+ function_name: 'test-function',
718
+ function_args: JSON.stringify(
719
+ {
720
+ arg1: 'value1',
721
+ arg2: 2,
722
+ },
723
+ null,
724
+ 2,
725
+ ),
726
+ duration_ms: 100,
727
+ success: true,
728
+ prompt_id: 'prompt-id-4',
729
+ tool_type: 'native',
730
+ },
731
+ });
732
+
733
+ expect(mockMetrics.recordToolCallMetrics).toHaveBeenCalledWith(
734
+ mockConfig,
735
+ 'test-function',
736
+ 100,
737
+ true,
738
+ undefined,
739
+ 'native',
740
+ );
741
+
742
+ expect(mockUiEvent.addEvent).toHaveBeenCalledWith({
743
+ ...event,
744
+ 'event.name': EVENT_TOOL_CALL,
745
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
746
+ });
747
+ });
748
+
749
+ it('should log a failed tool call with an error', () => {
750
+ const call: ErroredToolCall = {
751
+ status: 'error',
752
+ request: {
753
+ name: 'test-function',
754
+ args: {
755
+ arg1: 'value1',
756
+ arg2: 2,
757
+ },
758
+ callId: 'test-call-id',
759
+ isClientInitiated: true,
760
+ prompt_id: 'prompt-id-5',
761
+ },
762
+ response: {
763
+ callId: 'test-call-id',
764
+ responseParts: 'test-response',
765
+ resultDisplay: undefined,
766
+ error: {
767
+ name: 'test-error-type',
768
+ message: 'test-error',
769
+ },
770
+ errorType: ToolErrorType.UNKNOWN,
771
+ },
772
+ durationMs: 100,
773
+ };
774
+ const event = new ToolCallEvent(call);
775
+
776
+ logToolCall(mockConfig, event);
777
+
778
+ expect(mockLogger.emit).toHaveBeenCalledWith({
779
+ body: 'Tool call: test-function. Success: false. Duration: 100ms.',
780
+ attributes: {
781
+ 'session.id': 'test-session-id',
782
+ 'event.name': EVENT_TOOL_CALL,
783
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
784
+ function_name: 'test-function',
785
+ function_args: JSON.stringify(
786
+ {
787
+ arg1: 'value1',
788
+ arg2: 2,
789
+ },
790
+ null,
791
+ 2,
792
+ ),
793
+ duration_ms: 100,
794
+ success: false,
795
+ error: 'test-error',
796
+ 'error.message': 'test-error',
797
+ error_type: ToolErrorType.UNKNOWN,
798
+ 'error.type': ToolErrorType.UNKNOWN,
799
+ prompt_id: 'prompt-id-5',
800
+ tool_type: 'native',
801
+ },
802
+ });
803
+
804
+ expect(mockMetrics.recordToolCallMetrics).toHaveBeenCalledWith(
805
+ mockConfig,
806
+ 'test-function',
807
+ 100,
808
+ false,
809
+ undefined,
810
+ 'native',
811
+ );
812
+
813
+ expect(mockUiEvent.addEvent).toHaveBeenCalledWith({
814
+ ...event,
815
+ 'event.name': EVENT_TOOL_CALL,
816
+ 'event.timestamp': '2025-01-01T00:00:00.000Z',
817
+ });
818
+ });
819
+ });
820
+ });
projects/ui/qwen-code/packages/core/src/telemetry/loggers.ts ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { LogAttributes, LogRecord, logs } from '@opentelemetry/api-logs';
8
+ import { SemanticAttributes } from '@opentelemetry/semantic-conventions';
9
+ import { Config } from '../config/config.js';
10
+ import {
11
+ EVENT_API_ERROR,
12
+ EVENT_API_REQUEST,
13
+ EVENT_API_RESPONSE,
14
+ EVENT_CLI_CONFIG,
15
+ EVENT_FLASH_FALLBACK,
16
+ EVENT_IDE_CONNECTION,
17
+ EVENT_NEXT_SPEAKER_CHECK,
18
+ EVENT_SLASH_COMMAND,
19
+ EVENT_TOOL_CALL,
20
+ EVENT_USER_PROMPT,
21
+ SERVICE_NAME,
22
+ EVENT_CHAT_COMPRESSION,
23
+ EVENT_INVALID_CHUNK,
24
+ EVENT_CONTENT_RETRY,
25
+ EVENT_CONTENT_RETRY_FAILURE,
26
+ } from './constants.js';
27
+ import {
28
+ ApiErrorEvent,
29
+ ApiRequestEvent,
30
+ ApiResponseEvent,
31
+ FlashFallbackEvent,
32
+ IdeConnectionEvent,
33
+ KittySequenceOverflowEvent,
34
+ LoopDetectedEvent,
35
+ NextSpeakerCheckEvent,
36
+ SlashCommandEvent,
37
+ StartSessionEvent,
38
+ ToolCallEvent,
39
+ UserPromptEvent,
40
+ ChatCompressionEvent,
41
+ InvalidChunkEvent,
42
+ ContentRetryEvent,
43
+ ContentRetryFailureEvent,
44
+ } from './types.js';
45
+ import {
46
+ recordApiErrorMetrics,
47
+ recordTokenUsageMetrics,
48
+ recordApiResponseMetrics,
49
+ recordToolCallMetrics,
50
+ recordChatCompressionMetrics,
51
+ recordInvalidChunk,
52
+ recordContentRetry,
53
+ recordContentRetryFailure,
54
+ } from './metrics.js';
55
+ import { QwenLogger } from './qwen-logger/qwen-logger.js';
56
+ import { isTelemetrySdkInitialized } from './sdk.js';
57
+ import { uiTelemetryService, UiEvent } from './uiTelemetry.js';
58
+ import { safeJsonStringify } from '../utils/safeJsonStringify.js';
59
+
60
+ const shouldLogUserPrompts = (config: Config): boolean =>
61
+ config.getTelemetryLogPromptsEnabled();
62
+
63
+ function getCommonAttributes(config: Config): LogAttributes {
64
+ return {
65
+ 'session.id': config.getSessionId(),
66
+ };
67
+ }
68
+
69
+ export function logCliConfiguration(
70
+ config: Config,
71
+ event: StartSessionEvent,
72
+ ): void {
73
+ QwenLogger.getInstance(config)?.logStartSessionEvent(event);
74
+ if (!isTelemetrySdkInitialized()) return;
75
+
76
+ const attributes: LogAttributes = {
77
+ ...getCommonAttributes(config),
78
+ 'event.name': EVENT_CLI_CONFIG,
79
+ 'event.timestamp': new Date().toISOString(),
80
+ model: event.model,
81
+ embedding_model: event.embedding_model,
82
+ sandbox_enabled: event.sandbox_enabled,
83
+ core_tools_enabled: event.core_tools_enabled,
84
+ approval_mode: event.approval_mode,
85
+ api_key_enabled: event.api_key_enabled,
86
+ vertex_ai_enabled: event.vertex_ai_enabled,
87
+ log_user_prompts_enabled: event.telemetry_log_user_prompts_enabled,
88
+ file_filtering_respect_git_ignore: event.file_filtering_respect_git_ignore,
89
+ debug_mode: event.debug_enabled,
90
+ mcp_servers: event.mcp_servers,
91
+ };
92
+
93
+ const logger = logs.getLogger(SERVICE_NAME);
94
+ const logRecord: LogRecord = {
95
+ body: 'CLI configuration loaded.',
96
+ attributes,
97
+ };
98
+ logger.emit(logRecord);
99
+ }
100
+
101
+ export function logUserPrompt(config: Config, event: UserPromptEvent): void {
102
+ QwenLogger.getInstance(config)?.logNewPromptEvent(event);
103
+ if (!isTelemetrySdkInitialized()) return;
104
+
105
+ const attributes: LogAttributes = {
106
+ ...getCommonAttributes(config),
107
+ 'event.name': EVENT_USER_PROMPT,
108
+ 'event.timestamp': new Date().toISOString(),
109
+ prompt_length: event.prompt_length,
110
+ };
111
+
112
+ if (shouldLogUserPrompts(config)) {
113
+ attributes['prompt'] = event.prompt;
114
+ }
115
+
116
+ const logger = logs.getLogger(SERVICE_NAME);
117
+ const logRecord: LogRecord = {
118
+ body: `User prompt. Length: ${event.prompt_length}.`,
119
+ attributes,
120
+ };
121
+ logger.emit(logRecord);
122
+ }
123
+
124
+ export function logToolCall(config: Config, event: ToolCallEvent): void {
125
+ const uiEvent = {
126
+ ...event,
127
+ 'event.name': EVENT_TOOL_CALL,
128
+ 'event.timestamp': new Date().toISOString(),
129
+ } as UiEvent;
130
+ uiTelemetryService.addEvent(uiEvent);
131
+ QwenLogger.getInstance(config)?.logToolCallEvent(event);
132
+ if (!isTelemetrySdkInitialized()) return;
133
+
134
+ const attributes: LogAttributes = {
135
+ ...getCommonAttributes(config),
136
+ ...event,
137
+ 'event.name': EVENT_TOOL_CALL,
138
+ 'event.timestamp': new Date().toISOString(),
139
+ function_args: safeJsonStringify(event.function_args, 2),
140
+ };
141
+ if (event.error) {
142
+ attributes['error.message'] = event.error;
143
+ if (event.error_type) {
144
+ attributes['error.type'] = event.error_type;
145
+ }
146
+ }
147
+
148
+ const logger = logs.getLogger(SERVICE_NAME);
149
+ const logRecord: LogRecord = {
150
+ body: `Tool call: ${event.function_name}${event.decision ? `. Decision: ${event.decision}` : ''}. Success: ${event.success}. Duration: ${event.duration_ms}ms.`,
151
+ attributes,
152
+ };
153
+ logger.emit(logRecord);
154
+ recordToolCallMetrics(
155
+ config,
156
+ event.function_name,
157
+ event.duration_ms,
158
+ event.success,
159
+ event.decision,
160
+ event.tool_type,
161
+ );
162
+ }
163
+
164
+ export function logApiRequest(config: Config, event: ApiRequestEvent): void {
165
+ // QwenLogger.getInstance(config)?.logApiRequestEvent(event);
166
+ if (!isTelemetrySdkInitialized()) return;
167
+
168
+ const attributes: LogAttributes = {
169
+ ...getCommonAttributes(config),
170
+ ...event,
171
+ 'event.name': EVENT_API_REQUEST,
172
+ 'event.timestamp': new Date().toISOString(),
173
+ };
174
+
175
+ const logger = logs.getLogger(SERVICE_NAME);
176
+ const logRecord: LogRecord = {
177
+ body: `API request to ${event.model}.`,
178
+ attributes,
179
+ };
180
+ logger.emit(logRecord);
181
+ }
182
+
183
+ export function logFlashFallback(
184
+ config: Config,
185
+ event: FlashFallbackEvent,
186
+ ): void {
187
+ QwenLogger.getInstance(config)?.logFlashFallbackEvent(event);
188
+ if (!isTelemetrySdkInitialized()) return;
189
+
190
+ const attributes: LogAttributes = {
191
+ ...getCommonAttributes(config),
192
+ ...event,
193
+ 'event.name': EVENT_FLASH_FALLBACK,
194
+ 'event.timestamp': new Date().toISOString(),
195
+ };
196
+
197
+ const logger = logs.getLogger(SERVICE_NAME);
198
+ const logRecord: LogRecord = {
199
+ body: `Switching to flash as Fallback.`,
200
+ attributes,
201
+ };
202
+ logger.emit(logRecord);
203
+ }
204
+
205
+ export function logApiError(config: Config, event: ApiErrorEvent): void {
206
+ const uiEvent = {
207
+ ...event,
208
+ 'event.name': EVENT_API_ERROR,
209
+ 'event.timestamp': new Date().toISOString(),
210
+ } as UiEvent;
211
+ uiTelemetryService.addEvent(uiEvent);
212
+ QwenLogger.getInstance(config)?.logApiErrorEvent(event);
213
+ if (!isTelemetrySdkInitialized()) return;
214
+
215
+ const attributes: LogAttributes = {
216
+ ...getCommonAttributes(config),
217
+ ...event,
218
+ 'event.name': EVENT_API_ERROR,
219
+ 'event.timestamp': new Date().toISOString(),
220
+ ['error.message']: event.error,
221
+ model_name: event.model,
222
+ duration: event.duration_ms,
223
+ };
224
+
225
+ if (event.error_type) {
226
+ attributes['error.type'] = event.error_type;
227
+ }
228
+ if (typeof event.status_code === 'number') {
229
+ attributes[SemanticAttributes.HTTP_STATUS_CODE] = event.status_code;
230
+ }
231
+
232
+ const logger = logs.getLogger(SERVICE_NAME);
233
+ const logRecord: LogRecord = {
234
+ body: `API error for ${event.model}. Error: ${event.error}. Duration: ${event.duration_ms}ms.`,
235
+ attributes,
236
+ };
237
+ logger.emit(logRecord);
238
+ recordApiErrorMetrics(
239
+ config,
240
+ event.model,
241
+ event.duration_ms,
242
+ event.status_code,
243
+ event.error_type,
244
+ );
245
+ }
246
+
247
+ export function logApiResponse(config: Config, event: ApiResponseEvent): void {
248
+ const uiEvent = {
249
+ ...event,
250
+ 'event.name': EVENT_API_RESPONSE,
251
+ 'event.timestamp': new Date().toISOString(),
252
+ } as UiEvent;
253
+ uiTelemetryService.addEvent(uiEvent);
254
+ QwenLogger.getInstance(config)?.logApiResponseEvent(event);
255
+ if (!isTelemetrySdkInitialized()) return;
256
+ const attributes: LogAttributes = {
257
+ ...getCommonAttributes(config),
258
+ ...event,
259
+ 'event.name': EVENT_API_RESPONSE,
260
+ 'event.timestamp': new Date().toISOString(),
261
+ };
262
+ if (event.response_text) {
263
+ attributes['response_text'] = event.response_text;
264
+ }
265
+ if (event.error) {
266
+ attributes['error.message'] = event.error;
267
+ } else if (event.status_code) {
268
+ if (typeof event.status_code === 'number') {
269
+ attributes[SemanticAttributes.HTTP_STATUS_CODE] = event.status_code;
270
+ }
271
+ }
272
+
273
+ const logger = logs.getLogger(SERVICE_NAME);
274
+ const logRecord: LogRecord = {
275
+ body: `API response from ${event.model}. Status: ${event.status_code || 'N/A'}. Duration: ${event.duration_ms}ms.`,
276
+ attributes,
277
+ };
278
+ logger.emit(logRecord);
279
+ recordApiResponseMetrics(
280
+ config,
281
+ event.model,
282
+ event.duration_ms,
283
+ event.status_code,
284
+ event.error,
285
+ );
286
+ recordTokenUsageMetrics(
287
+ config,
288
+ event.model,
289
+ event.input_token_count,
290
+ 'input',
291
+ );
292
+ recordTokenUsageMetrics(
293
+ config,
294
+ event.model,
295
+ event.output_token_count,
296
+ 'output',
297
+ );
298
+ recordTokenUsageMetrics(
299
+ config,
300
+ event.model,
301
+ event.cached_content_token_count,
302
+ 'cache',
303
+ );
304
+ recordTokenUsageMetrics(
305
+ config,
306
+ event.model,
307
+ event.thoughts_token_count,
308
+ 'thought',
309
+ );
310
+ recordTokenUsageMetrics(config, event.model, event.tool_token_count, 'tool');
311
+ }
312
+
313
+ export function logLoopDetected(
314
+ config: Config,
315
+ event: LoopDetectedEvent,
316
+ ): void {
317
+ QwenLogger.getInstance(config)?.logLoopDetectedEvent(event);
318
+ if (!isTelemetrySdkInitialized()) return;
319
+
320
+ const attributes: LogAttributes = {
321
+ ...getCommonAttributes(config),
322
+ ...event,
323
+ };
324
+
325
+ const logger = logs.getLogger(SERVICE_NAME);
326
+ const logRecord: LogRecord = {
327
+ body: `Loop detected. Type: ${event.loop_type}.`,
328
+ attributes,
329
+ };
330
+ logger.emit(logRecord);
331
+ }
332
+
333
+ export function logNextSpeakerCheck(
334
+ config: Config,
335
+ event: NextSpeakerCheckEvent,
336
+ ): void {
337
+ QwenLogger.getInstance(config)?.logNextSpeakerCheck(event);
338
+ if (!isTelemetrySdkInitialized()) return;
339
+
340
+ const attributes: LogAttributes = {
341
+ ...getCommonAttributes(config),
342
+ ...event,
343
+ 'event.name': EVENT_NEXT_SPEAKER_CHECK,
344
+ };
345
+
346
+ const logger = logs.getLogger(SERVICE_NAME);
347
+ const logRecord: LogRecord = {
348
+ body: `Next speaker check.`,
349
+ attributes,
350
+ };
351
+ logger.emit(logRecord);
352
+ }
353
+
354
+ export function logSlashCommand(
355
+ config: Config,
356
+ event: SlashCommandEvent,
357
+ ): void {
358
+ QwenLogger.getInstance(config)?.logSlashCommandEvent(event);
359
+ if (!isTelemetrySdkInitialized()) return;
360
+
361
+ const attributes: LogAttributes = {
362
+ ...getCommonAttributes(config),
363
+ ...event,
364
+ 'event.name': EVENT_SLASH_COMMAND,
365
+ };
366
+
367
+ const logger = logs.getLogger(SERVICE_NAME);
368
+ const logRecord: LogRecord = {
369
+ body: `Slash command: ${event.command}.`,
370
+ attributes,
371
+ };
372
+ logger.emit(logRecord);
373
+ }
374
+
375
+ export function logIdeConnection(
376
+ config: Config,
377
+ event: IdeConnectionEvent,
378
+ ): void {
379
+ QwenLogger.getInstance(config)?.logIdeConnectionEvent(event);
380
+ if (!isTelemetrySdkInitialized()) return;
381
+
382
+ const attributes: LogAttributes = {
383
+ ...getCommonAttributes(config),
384
+ ...event,
385
+ 'event.name': EVENT_IDE_CONNECTION,
386
+ };
387
+
388
+ const logger = logs.getLogger(SERVICE_NAME);
389
+ const logRecord: LogRecord = {
390
+ body: `Ide connection. Type: ${event.connection_type}.`,
391
+ attributes,
392
+ };
393
+ logger.emit(logRecord);
394
+ }
395
+
396
+ export function logChatCompression(
397
+ config: Config,
398
+ event: ChatCompressionEvent,
399
+ ): void {
400
+ QwenLogger.getInstance(config)?.logChatCompressionEvent(event);
401
+
402
+ const attributes: LogAttributes = {
403
+ ...getCommonAttributes(config),
404
+ ...event,
405
+ 'event.name': EVENT_CHAT_COMPRESSION,
406
+ };
407
+
408
+ const logger = logs.getLogger(SERVICE_NAME);
409
+ const logRecord: LogRecord = {
410
+ body: `Chat compression (Saved ${event.tokens_before - event.tokens_after} tokens)`,
411
+ attributes,
412
+ };
413
+ logger.emit(logRecord);
414
+
415
+ recordChatCompressionMetrics(config, {
416
+ tokens_before: event.tokens_before,
417
+ tokens_after: event.tokens_after,
418
+ });
419
+ }
420
+
421
+ export function logKittySequenceOverflow(
422
+ config: Config,
423
+ event: KittySequenceOverflowEvent,
424
+ ): void {
425
+ QwenLogger.getInstance(config)?.logKittySequenceOverflowEvent(event);
426
+ if (!isTelemetrySdkInitialized()) return;
427
+ const attributes: LogAttributes = {
428
+ ...getCommonAttributes(config),
429
+ ...event,
430
+ };
431
+ const logger = logs.getLogger(SERVICE_NAME);
432
+ const logRecord: LogRecord = {
433
+ body: `Kitty sequence buffer overflow: ${event.sequence_length} bytes`,
434
+ attributes,
435
+ };
436
+ logger.emit(logRecord);
437
+ }
438
+ export function logInvalidChunk(
439
+ config: Config,
440
+ event: InvalidChunkEvent,
441
+ ): void {
442
+ QwenLogger.getInstance(config)?.logInvalidChunkEvent(event);
443
+ if (!isTelemetrySdkInitialized()) return;
444
+
445
+ const attributes: LogAttributes = {
446
+ ...getCommonAttributes(config),
447
+ 'event.name': EVENT_INVALID_CHUNK,
448
+ 'event.timestamp': event['event.timestamp'],
449
+ };
450
+
451
+ if (event.error_message) {
452
+ attributes['error.message'] = event.error_message;
453
+ }
454
+
455
+ const logger = logs.getLogger(SERVICE_NAME);
456
+ const logRecord: LogRecord = {
457
+ body: `Invalid chunk received from stream.`,
458
+ attributes,
459
+ };
460
+ logger.emit(logRecord);
461
+ recordInvalidChunk(config);
462
+ }
463
+
464
+ export function logContentRetry(
465
+ config: Config,
466
+ event: ContentRetryEvent,
467
+ ): void {
468
+ QwenLogger.getInstance(config)?.logContentRetryEvent(event);
469
+ if (!isTelemetrySdkInitialized()) return;
470
+
471
+ const attributes: LogAttributes = {
472
+ ...getCommonAttributes(config),
473
+ ...event,
474
+ 'event.name': EVENT_CONTENT_RETRY,
475
+ };
476
+
477
+ const logger = logs.getLogger(SERVICE_NAME);
478
+ const logRecord: LogRecord = {
479
+ body: `Content retry attempt ${event.attempt_number} due to ${event.error_type}.`,
480
+ attributes,
481
+ };
482
+ logger.emit(logRecord);
483
+ recordContentRetry(config);
484
+ }
485
+
486
+ export function logContentRetryFailure(
487
+ config: Config,
488
+ event: ContentRetryFailureEvent,
489
+ ): void {
490
+ QwenLogger.getInstance(config)?.logContentRetryFailureEvent(event);
491
+ if (!isTelemetrySdkInitialized()) return;
492
+
493
+ const attributes: LogAttributes = {
494
+ ...getCommonAttributes(config),
495
+ ...event,
496
+ 'event.name': EVENT_CONTENT_RETRY_FAILURE,
497
+ };
498
+
499
+ const logger = logs.getLogger(SERVICE_NAME);
500
+ const logRecord: LogRecord = {
501
+ body: `All content retries failed after ${event.total_attempts} attempts.`,
502
+ attributes,
503
+ };
504
+ logger.emit(logRecord);
505
+ recordContentRetryFailure(config);
506
+ }
projects/ui/qwen-code/packages/core/src/telemetry/metrics.test.ts ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
8
+ import type {
9
+ Counter,
10
+ Meter,
11
+ Attributes,
12
+ Context,
13
+ Histogram,
14
+ } from '@opentelemetry/api';
15
+ import { Config } from '../config/config.js';
16
+ import { FileOperation } from './metrics.js';
17
+ import { makeFakeConfig } from '../test-utils/config.js';
18
+
19
+ const mockCounterAddFn: Mock<
20
+ (value: number, attributes?: Attributes, context?: Context) => void
21
+ > = vi.fn();
22
+ const mockHistogramRecordFn: Mock<
23
+ (value: number, attributes?: Attributes, context?: Context) => void
24
+ > = vi.fn();
25
+
26
+ const mockCreateCounterFn: Mock<(name: string, options?: unknown) => Counter> =
27
+ vi.fn();
28
+ const mockCreateHistogramFn: Mock<
29
+ (name: string, options?: unknown) => Histogram
30
+ > = vi.fn();
31
+
32
+ const mockCounterInstance: Counter = {
33
+ add: mockCounterAddFn,
34
+ } as Partial<Counter> as Counter;
35
+
36
+ const mockHistogramInstance: Histogram = {
37
+ record: mockHistogramRecordFn,
38
+ } as Partial<Histogram> as Histogram;
39
+
40
+ const mockMeterInstance: Meter = {
41
+ createCounter: mockCreateCounterFn.mockReturnValue(mockCounterInstance),
42
+ createHistogram: mockCreateHistogramFn.mockReturnValue(mockHistogramInstance),
43
+ } as Partial<Meter> as Meter;
44
+
45
+ function originalOtelMockFactory() {
46
+ return {
47
+ metrics: {
48
+ getMeter: vi.fn(),
49
+ },
50
+ ValueType: {
51
+ INT: 1,
52
+ },
53
+ diag: {
54
+ setLogger: vi.fn(),
55
+ },
56
+ };
57
+ }
58
+
59
+ vi.mock('@opentelemetry/api');
60
+
61
+ describe('Telemetry Metrics', () => {
62
+ let initializeMetricsModule: typeof import('./metrics.js').initializeMetrics;
63
+ let recordTokenUsageMetricsModule: typeof import('./metrics.js').recordTokenUsageMetrics;
64
+ let recordFileOperationMetricModule: typeof import('./metrics.js').recordFileOperationMetric;
65
+ let recordChatCompressionMetricsModule: typeof import('./metrics.js').recordChatCompressionMetrics;
66
+
67
+ beforeEach(async () => {
68
+ vi.resetModules();
69
+ vi.doMock('@opentelemetry/api', () => {
70
+ const actualApi = originalOtelMockFactory();
71
+ (actualApi.metrics.getMeter as Mock).mockReturnValue(mockMeterInstance);
72
+ return actualApi;
73
+ });
74
+
75
+ const metricsJsModule = await import('./metrics.js');
76
+ initializeMetricsModule = metricsJsModule.initializeMetrics;
77
+ recordTokenUsageMetricsModule = metricsJsModule.recordTokenUsageMetrics;
78
+ recordFileOperationMetricModule = metricsJsModule.recordFileOperationMetric;
79
+ recordChatCompressionMetricsModule =
80
+ metricsJsModule.recordChatCompressionMetrics;
81
+
82
+ const otelApiModule = await import('@opentelemetry/api');
83
+
84
+ mockCounterAddFn.mockClear();
85
+ mockCreateCounterFn.mockClear();
86
+ mockCreateHistogramFn.mockClear();
87
+ mockHistogramRecordFn.mockClear();
88
+ (otelApiModule.metrics.getMeter as Mock).mockClear();
89
+
90
+ (otelApiModule.metrics.getMeter as Mock).mockReturnValue(mockMeterInstance);
91
+ mockCreateCounterFn.mockReturnValue(mockCounterInstance);
92
+ mockCreateHistogramFn.mockReturnValue(mockHistogramInstance);
93
+ });
94
+
95
+ describe('recordChatCompressionMetrics', () => {
96
+ it('does not record metrics if not initialized', () => {
97
+ const lol = makeFakeConfig({});
98
+
99
+ recordChatCompressionMetricsModule(lol, {
100
+ tokens_after: 100,
101
+ tokens_before: 200,
102
+ });
103
+
104
+ expect(mockCounterAddFn).not.toHaveBeenCalled();
105
+ });
106
+
107
+ it('records token compression with the correct attributes', () => {
108
+ const config = makeFakeConfig({});
109
+ initializeMetricsModule(config);
110
+
111
+ recordChatCompressionMetricsModule(config, {
112
+ tokens_after: 100,
113
+ tokens_before: 200,
114
+ });
115
+
116
+ expect(mockCounterAddFn).toHaveBeenCalledWith(1, {
117
+ 'session.id': 'test-session-id',
118
+ tokens_after: 100,
119
+ tokens_before: 200,
120
+ });
121
+ });
122
+ });
123
+
124
+ describe('recordTokenUsageMetrics', () => {
125
+ const mockConfig = {
126
+ getSessionId: () => 'test-session-id',
127
+ } as unknown as Config;
128
+
129
+ it('should not record metrics if not initialized', () => {
130
+ recordTokenUsageMetricsModule(mockConfig, 'gemini-pro', 100, 'input');
131
+ expect(mockCounterAddFn).not.toHaveBeenCalled();
132
+ });
133
+
134
+ it('should record token usage with the correct attributes', () => {
135
+ initializeMetricsModule(mockConfig);
136
+ recordTokenUsageMetricsModule(mockConfig, 'gemini-pro', 100, 'input');
137
+ expect(mockCounterAddFn).toHaveBeenCalledTimes(2);
138
+ expect(mockCounterAddFn).toHaveBeenNthCalledWith(1, 1, {
139
+ 'session.id': 'test-session-id',
140
+ });
141
+ expect(mockCounterAddFn).toHaveBeenNthCalledWith(2, 100, {
142
+ 'session.id': 'test-session-id',
143
+ model: 'gemini-pro',
144
+ type: 'input',
145
+ });
146
+ });
147
+
148
+ it('should record token usage for different types', () => {
149
+ initializeMetricsModule(mockConfig);
150
+ mockCounterAddFn.mockClear();
151
+
152
+ recordTokenUsageMetricsModule(mockConfig, 'gemini-pro', 50, 'output');
153
+ expect(mockCounterAddFn).toHaveBeenCalledWith(50, {
154
+ 'session.id': 'test-session-id',
155
+ model: 'gemini-pro',
156
+ type: 'output',
157
+ });
158
+
159
+ recordTokenUsageMetricsModule(mockConfig, 'gemini-pro', 25, 'thought');
160
+ expect(mockCounterAddFn).toHaveBeenCalledWith(25, {
161
+ 'session.id': 'test-session-id',
162
+ model: 'gemini-pro',
163
+ type: 'thought',
164
+ });
165
+
166
+ recordTokenUsageMetricsModule(mockConfig, 'gemini-pro', 75, 'cache');
167
+ expect(mockCounterAddFn).toHaveBeenCalledWith(75, {
168
+ 'session.id': 'test-session-id',
169
+ model: 'gemini-pro',
170
+ type: 'cache',
171
+ });
172
+
173
+ recordTokenUsageMetricsModule(mockConfig, 'gemini-pro', 125, 'tool');
174
+ expect(mockCounterAddFn).toHaveBeenCalledWith(125, {
175
+ 'session.id': 'test-session-id',
176
+ model: 'gemini-pro',
177
+ type: 'tool',
178
+ });
179
+ });
180
+
181
+ it('should handle different models', () => {
182
+ initializeMetricsModule(mockConfig);
183
+ mockCounterAddFn.mockClear();
184
+
185
+ recordTokenUsageMetricsModule(mockConfig, 'gemini-ultra', 200, 'input');
186
+ expect(mockCounterAddFn).toHaveBeenCalledWith(200, {
187
+ 'session.id': 'test-session-id',
188
+ model: 'gemini-ultra',
189
+ type: 'input',
190
+ });
191
+ });
192
+ });
193
+
194
+ describe('recordFileOperationMetric', () => {
195
+ const mockConfig = {
196
+ getSessionId: () => 'test-session-id',
197
+ } as unknown as Config;
198
+
199
+ it('should not record metrics if not initialized', () => {
200
+ recordFileOperationMetricModule(
201
+ mockConfig,
202
+ FileOperation.CREATE,
203
+ 10,
204
+ 'text/plain',
205
+ 'txt',
206
+ );
207
+ expect(mockCounterAddFn).not.toHaveBeenCalled();
208
+ });
209
+
210
+ it('should record file creation with all attributes', () => {
211
+ initializeMetricsModule(mockConfig);
212
+ recordFileOperationMetricModule(
213
+ mockConfig,
214
+ FileOperation.CREATE,
215
+ 10,
216
+ 'text/plain',
217
+ 'txt',
218
+ );
219
+
220
+ expect(mockCounterAddFn).toHaveBeenCalledTimes(2);
221
+ expect(mockCounterAddFn).toHaveBeenNthCalledWith(1, 1, {
222
+ 'session.id': 'test-session-id',
223
+ });
224
+ expect(mockCounterAddFn).toHaveBeenNthCalledWith(2, 1, {
225
+ 'session.id': 'test-session-id',
226
+ operation: FileOperation.CREATE,
227
+ lines: 10,
228
+ mimetype: 'text/plain',
229
+ extension: 'txt',
230
+ });
231
+ });
232
+
233
+ it('should record file read with minimal attributes', () => {
234
+ initializeMetricsModule(mockConfig);
235
+ mockCounterAddFn.mockClear();
236
+
237
+ recordFileOperationMetricModule(mockConfig, FileOperation.READ);
238
+ expect(mockCounterAddFn).toHaveBeenCalledWith(1, {
239
+ 'session.id': 'test-session-id',
240
+ operation: FileOperation.READ,
241
+ });
242
+ });
243
+
244
+ it('should record file update with some attributes', () => {
245
+ initializeMetricsModule(mockConfig);
246
+ mockCounterAddFn.mockClear();
247
+
248
+ recordFileOperationMetricModule(
249
+ mockConfig,
250
+ FileOperation.UPDATE,
251
+ undefined,
252
+ 'application/javascript',
253
+ );
254
+ expect(mockCounterAddFn).toHaveBeenCalledWith(1, {
255
+ 'session.id': 'test-session-id',
256
+ operation: FileOperation.UPDATE,
257
+ mimetype: 'application/javascript',
258
+ });
259
+ });
260
+
261
+ it('should include diffStat when provided', () => {
262
+ initializeMetricsModule(mockConfig);
263
+ mockCounterAddFn.mockClear();
264
+
265
+ const diffStat = {
266
+ ai_added_lines: 5,
267
+ ai_removed_lines: 2,
268
+ user_added_lines: 3,
269
+ user_removed_lines: 1,
270
+ };
271
+
272
+ recordFileOperationMetricModule(
273
+ mockConfig,
274
+ FileOperation.UPDATE,
275
+ undefined,
276
+ undefined,
277
+ undefined,
278
+ diffStat,
279
+ );
280
+
281
+ expect(mockCounterAddFn).toHaveBeenCalledWith(1, {
282
+ 'session.id': 'test-session-id',
283
+ operation: FileOperation.UPDATE,
284
+ ai_added_lines: 5,
285
+ ai_removed_lines: 2,
286
+ user_added_lines: 3,
287
+ user_removed_lines: 1,
288
+ });
289
+ });
290
+
291
+ it('should not include diffStat attributes when diffStat is not provided', () => {
292
+ initializeMetricsModule(mockConfig);
293
+ mockCounterAddFn.mockClear();
294
+
295
+ recordFileOperationMetricModule(
296
+ mockConfig,
297
+ FileOperation.UPDATE,
298
+ 10,
299
+ 'text/plain',
300
+ 'txt',
301
+ undefined,
302
+ );
303
+
304
+ expect(mockCounterAddFn).toHaveBeenCalledWith(1, {
305
+ 'session.id': 'test-session-id',
306
+ operation: FileOperation.UPDATE,
307
+ lines: 10,
308
+ mimetype: 'text/plain',
309
+ extension: 'txt',
310
+ });
311
+ });
312
+
313
+ it('should handle diffStat with all zero values', () => {
314
+ initializeMetricsModule(mockConfig);
315
+ mockCounterAddFn.mockClear();
316
+
317
+ const diffStat = {
318
+ ai_added_lines: 0,
319
+ ai_removed_lines: 0,
320
+ user_added_lines: 0,
321
+ user_removed_lines: 0,
322
+ };
323
+
324
+ recordFileOperationMetricModule(
325
+ mockConfig,
326
+ FileOperation.UPDATE,
327
+ undefined,
328
+ undefined,
329
+ undefined,
330
+ diffStat,
331
+ );
332
+
333
+ expect(mockCounterAddFn).toHaveBeenCalledWith(1, {
334
+ 'session.id': 'test-session-id',
335
+ operation: FileOperation.UPDATE,
336
+ ai_added_lines: 0,
337
+ ai_removed_lines: 0,
338
+ user_added_lines: 0,
339
+ user_removed_lines: 0,
340
+ });
341
+ });
342
+ });
343
+ });
projects/ui/qwen-code/packages/core/src/telemetry/metrics.ts ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ metrics,
9
+ Attributes,
10
+ ValueType,
11
+ Meter,
12
+ Counter,
13
+ Histogram,
14
+ } from '@opentelemetry/api';
15
+ import {
16
+ SERVICE_NAME,
17
+ METRIC_TOOL_CALL_COUNT,
18
+ METRIC_TOOL_CALL_LATENCY,
19
+ METRIC_API_REQUEST_COUNT,
20
+ METRIC_API_REQUEST_LATENCY,
21
+ METRIC_TOKEN_USAGE,
22
+ METRIC_SESSION_COUNT,
23
+ METRIC_FILE_OPERATION_COUNT,
24
+ EVENT_CHAT_COMPRESSION,
25
+ METRIC_INVALID_CHUNK_COUNT,
26
+ METRIC_CONTENT_RETRY_COUNT,
27
+ METRIC_CONTENT_RETRY_FAILURE_COUNT,
28
+ } from './constants.js';
29
+ import { Config } from '../config/config.js';
30
+ import { DiffStat } from '../tools/tools.js';
31
+
32
+ export enum FileOperation {
33
+ CREATE = 'create',
34
+ READ = 'read',
35
+ UPDATE = 'update',
36
+ }
37
+
38
+ let cliMeter: Meter | undefined;
39
+ let toolCallCounter: Counter | undefined;
40
+ let toolCallLatencyHistogram: Histogram | undefined;
41
+ let apiRequestCounter: Counter | undefined;
42
+ let apiRequestLatencyHistogram: Histogram | undefined;
43
+ let tokenUsageCounter: Counter | undefined;
44
+ let fileOperationCounter: Counter | undefined;
45
+ let chatCompressionCounter: Counter | undefined;
46
+ let invalidChunkCounter: Counter | undefined;
47
+ let contentRetryCounter: Counter | undefined;
48
+ let contentRetryFailureCounter: Counter | undefined;
49
+ let isMetricsInitialized = false;
50
+
51
+ function getCommonAttributes(config: Config): Attributes {
52
+ return {
53
+ 'session.id': config.getSessionId(),
54
+ };
55
+ }
56
+
57
+ export function getMeter(): Meter | undefined {
58
+ if (!cliMeter) {
59
+ cliMeter = metrics.getMeter(SERVICE_NAME);
60
+ }
61
+ return cliMeter;
62
+ }
63
+
64
+ export function initializeMetrics(config: Config): void {
65
+ if (isMetricsInitialized) return;
66
+
67
+ const meter = getMeter();
68
+ if (!meter) return;
69
+
70
+ toolCallCounter = meter.createCounter(METRIC_TOOL_CALL_COUNT, {
71
+ description: 'Counts tool calls, tagged by function name and success.',
72
+ valueType: ValueType.INT,
73
+ });
74
+ toolCallLatencyHistogram = meter.createHistogram(METRIC_TOOL_CALL_LATENCY, {
75
+ description: 'Latency of tool calls in milliseconds.',
76
+ unit: 'ms',
77
+ valueType: ValueType.INT,
78
+ });
79
+ apiRequestCounter = meter.createCounter(METRIC_API_REQUEST_COUNT, {
80
+ description: 'Counts API requests, tagged by model and status.',
81
+ valueType: ValueType.INT,
82
+ });
83
+ apiRequestLatencyHistogram = meter.createHistogram(
84
+ METRIC_API_REQUEST_LATENCY,
85
+ {
86
+ description: 'Latency of API requests in milliseconds.',
87
+ unit: 'ms',
88
+ valueType: ValueType.INT,
89
+ },
90
+ );
91
+ tokenUsageCounter = meter.createCounter(METRIC_TOKEN_USAGE, {
92
+ description: 'Counts the total number of tokens used.',
93
+ valueType: ValueType.INT,
94
+ });
95
+ fileOperationCounter = meter.createCounter(METRIC_FILE_OPERATION_COUNT, {
96
+ description: 'Counts file operations (create, read, update).',
97
+ valueType: ValueType.INT,
98
+ });
99
+ chatCompressionCounter = meter.createCounter(EVENT_CHAT_COMPRESSION, {
100
+ description: 'Counts chat compression events.',
101
+ valueType: ValueType.INT,
102
+ });
103
+
104
+ // New counters for content errors
105
+ invalidChunkCounter = meter.createCounter(METRIC_INVALID_CHUNK_COUNT, {
106
+ description: 'Counts invalid chunks received from a stream.',
107
+ valueType: ValueType.INT,
108
+ });
109
+ contentRetryCounter = meter.createCounter(METRIC_CONTENT_RETRY_COUNT, {
110
+ description: 'Counts retries due to content errors (e.g., empty stream).',
111
+ valueType: ValueType.INT,
112
+ });
113
+ contentRetryFailureCounter = meter.createCounter(
114
+ METRIC_CONTENT_RETRY_FAILURE_COUNT,
115
+ {
116
+ description: 'Counts occurrences of all content retries failing.',
117
+ valueType: ValueType.INT,
118
+ },
119
+ );
120
+
121
+ const sessionCounter = meter.createCounter(METRIC_SESSION_COUNT, {
122
+ description: 'Count of CLI sessions started.',
123
+ valueType: ValueType.INT,
124
+ });
125
+ sessionCounter.add(1, getCommonAttributes(config));
126
+ isMetricsInitialized = true;
127
+ }
128
+
129
+ export function recordChatCompressionMetrics(
130
+ config: Config,
131
+ args: { tokens_before: number; tokens_after: number },
132
+ ) {
133
+ if (!chatCompressionCounter || !isMetricsInitialized) return;
134
+ chatCompressionCounter.add(1, {
135
+ ...getCommonAttributes(config),
136
+ ...args,
137
+ });
138
+ }
139
+
140
+ export function recordToolCallMetrics(
141
+ config: Config,
142
+ functionName: string,
143
+ durationMs: number,
144
+ success: boolean,
145
+ decision?: 'accept' | 'reject' | 'modify' | 'auto_accept',
146
+ tool_type?: 'native' | 'mcp',
147
+ ): void {
148
+ if (!toolCallCounter || !toolCallLatencyHistogram || !isMetricsInitialized)
149
+ return;
150
+
151
+ const metricAttributes: Attributes = {
152
+ ...getCommonAttributes(config),
153
+ function_name: functionName,
154
+ success,
155
+ decision,
156
+ tool_type,
157
+ };
158
+ toolCallCounter.add(1, metricAttributes);
159
+ toolCallLatencyHistogram.record(durationMs, {
160
+ ...getCommonAttributes(config),
161
+ function_name: functionName,
162
+ });
163
+ }
164
+
165
+ export function recordTokenUsageMetrics(
166
+ config: Config,
167
+ model: string,
168
+ tokenCount: number,
169
+ type: 'input' | 'output' | 'thought' | 'cache' | 'tool',
170
+ ): void {
171
+ if (!tokenUsageCounter || !isMetricsInitialized) return;
172
+ tokenUsageCounter.add(tokenCount, {
173
+ ...getCommonAttributes(config),
174
+ model,
175
+ type,
176
+ });
177
+ }
178
+
179
+ export function recordApiResponseMetrics(
180
+ config: Config,
181
+ model: string,
182
+ durationMs: number,
183
+ statusCode?: number | string,
184
+ error?: string,
185
+ ): void {
186
+ if (
187
+ !apiRequestCounter ||
188
+ !apiRequestLatencyHistogram ||
189
+ !isMetricsInitialized
190
+ )
191
+ return;
192
+ const metricAttributes: Attributes = {
193
+ ...getCommonAttributes(config),
194
+ model,
195
+ status_code: statusCode ?? (error ? 'error' : 'ok'),
196
+ };
197
+ apiRequestCounter.add(1, metricAttributes);
198
+ apiRequestLatencyHistogram.record(durationMs, {
199
+ ...getCommonAttributes(config),
200
+ model,
201
+ });
202
+ }
203
+
204
+ export function recordApiErrorMetrics(
205
+ config: Config,
206
+ model: string,
207
+ durationMs: number,
208
+ statusCode?: number | string,
209
+ errorType?: string,
210
+ ): void {
211
+ if (
212
+ !apiRequestCounter ||
213
+ !apiRequestLatencyHistogram ||
214
+ !isMetricsInitialized
215
+ )
216
+ return;
217
+ const metricAttributes: Attributes = {
218
+ ...getCommonAttributes(config),
219
+ model,
220
+ status_code: statusCode ?? 'error',
221
+ error_type: errorType ?? 'unknown',
222
+ };
223
+ apiRequestCounter.add(1, metricAttributes);
224
+ apiRequestLatencyHistogram.record(durationMs, {
225
+ ...getCommonAttributes(config),
226
+ model,
227
+ });
228
+ }
229
+
230
+ export function recordFileOperationMetric(
231
+ config: Config,
232
+ operation: FileOperation,
233
+ lines?: number,
234
+ mimetype?: string,
235
+ extension?: string,
236
+ diffStat?: DiffStat,
237
+ ): void {
238
+ if (!fileOperationCounter || !isMetricsInitialized) return;
239
+ const attributes: Attributes = {
240
+ ...getCommonAttributes(config),
241
+ operation,
242
+ };
243
+ if (lines !== undefined) attributes['lines'] = lines;
244
+ if (mimetype !== undefined) attributes['mimetype'] = mimetype;
245
+ if (extension !== undefined) attributes['extension'] = extension;
246
+ if (diffStat !== undefined) {
247
+ attributes['ai_added_lines'] = diffStat.ai_added_lines;
248
+ attributes['ai_removed_lines'] = diffStat.ai_removed_lines;
249
+ attributes['user_added_lines'] = diffStat.user_added_lines;
250
+ attributes['user_removed_lines'] = diffStat.user_removed_lines;
251
+ }
252
+ fileOperationCounter.add(1, attributes);
253
+ }
254
+
255
+ // --- New Metric Recording Functions ---
256
+
257
+ /**
258
+ * Records a metric for when an invalid chunk is received from a stream.
259
+ */
260
+ export function recordInvalidChunk(config: Config): void {
261
+ if (!invalidChunkCounter || !isMetricsInitialized) return;
262
+ invalidChunkCounter.add(1, getCommonAttributes(config));
263
+ }
264
+
265
+ /**
266
+ * Records a metric for when a retry is triggered due to a content error.
267
+ */
268
+ export function recordContentRetry(config: Config): void {
269
+ if (!contentRetryCounter || !isMetricsInitialized) return;
270
+ contentRetryCounter.add(1, getCommonAttributes(config));
271
+ }
272
+
273
+ /**
274
+ * Records a metric for when all content error retries have failed for a request.
275
+ */
276
+ export function recordContentRetryFailure(config: Config): void {
277
+ if (!contentRetryFailureCounter || !isMetricsInitialized) return;
278
+ contentRetryFailureCounter.add(1, getCommonAttributes(config));
279
+ }
projects/ui/qwen-code/packages/core/src/telemetry/sdk.test.ts ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 { Config } from '../config/config.js';
9
+ import { initializeTelemetry, shutdownTelemetry } from './sdk.js';
10
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
11
+ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-grpc';
12
+ import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
13
+ import { OTLPTraceExporter as OTLPTraceExporterHttp } from '@opentelemetry/exporter-trace-otlp-http';
14
+ import { OTLPLogExporter as OTLPLogExporterHttp } from '@opentelemetry/exporter-logs-otlp-http';
15
+ import { OTLPMetricExporter as OTLPMetricExporterHttp } from '@opentelemetry/exporter-metrics-otlp-http';
16
+ import { NodeSDK } from '@opentelemetry/sdk-node';
17
+
18
+ vi.mock('@opentelemetry/exporter-trace-otlp-grpc');
19
+ vi.mock('@opentelemetry/exporter-logs-otlp-grpc');
20
+ vi.mock('@opentelemetry/exporter-metrics-otlp-grpc');
21
+ vi.mock('@opentelemetry/exporter-trace-otlp-http');
22
+ vi.mock('@opentelemetry/exporter-logs-otlp-http');
23
+ vi.mock('@opentelemetry/exporter-metrics-otlp-http');
24
+ vi.mock('@opentelemetry/sdk-node');
25
+
26
+ describe('Telemetry SDK', () => {
27
+ let mockConfig: Config;
28
+
29
+ beforeEach(() => {
30
+ vi.clearAllMocks();
31
+ mockConfig = {
32
+ getTelemetryEnabled: () => true,
33
+ getTelemetryOtlpEndpoint: () => 'http://localhost:4317',
34
+ getTelemetryOtlpProtocol: () => 'grpc',
35
+ getTelemetryOutfile: () => undefined,
36
+ getDebugMode: () => false,
37
+ getSessionId: () => 'test-session',
38
+ } as unknown as Config;
39
+ });
40
+
41
+ afterEach(async () => {
42
+ await shutdownTelemetry(mockConfig);
43
+ });
44
+
45
+ it('should use gRPC exporters when protocol is grpc', () => {
46
+ initializeTelemetry(mockConfig);
47
+
48
+ expect(OTLPTraceExporter).toHaveBeenCalledWith({
49
+ url: 'http://localhost:4317',
50
+ compression: 'gzip',
51
+ });
52
+ expect(OTLPLogExporter).toHaveBeenCalledWith({
53
+ url: 'http://localhost:4317',
54
+ compression: 'gzip',
55
+ });
56
+ expect(OTLPMetricExporter).toHaveBeenCalledWith({
57
+ url: 'http://localhost:4317',
58
+ compression: 'gzip',
59
+ });
60
+ expect(NodeSDK.prototype.start).toHaveBeenCalled();
61
+ });
62
+
63
+ it('should use HTTP exporters when protocol is http', () => {
64
+ vi.spyOn(mockConfig, 'getTelemetryEnabled').mockReturnValue(true);
65
+ vi.spyOn(mockConfig, 'getTelemetryOtlpProtocol').mockReturnValue('http');
66
+ vi.spyOn(mockConfig, 'getTelemetryOtlpEndpoint').mockReturnValue(
67
+ 'http://localhost:4318',
68
+ );
69
+
70
+ initializeTelemetry(mockConfig);
71
+
72
+ expect(OTLPTraceExporterHttp).toHaveBeenCalledWith({
73
+ url: 'http://localhost:4318/',
74
+ });
75
+ expect(OTLPLogExporterHttp).toHaveBeenCalledWith({
76
+ url: 'http://localhost:4318/',
77
+ });
78
+ expect(OTLPMetricExporterHttp).toHaveBeenCalledWith({
79
+ url: 'http://localhost:4318/',
80
+ });
81
+ expect(NodeSDK.prototype.start).toHaveBeenCalled();
82
+ });
83
+
84
+ it('should parse gRPC endpoint correctly', () => {
85
+ vi.spyOn(mockConfig, 'getTelemetryOtlpEndpoint').mockReturnValue(
86
+ 'https://my-collector.com',
87
+ );
88
+ initializeTelemetry(mockConfig);
89
+ expect(OTLPTraceExporter).toHaveBeenCalledWith(
90
+ expect.objectContaining({ url: 'https://my-collector.com' }),
91
+ );
92
+ });
93
+
94
+ it('should parse HTTP endpoint correctly', () => {
95
+ vi.spyOn(mockConfig, 'getTelemetryOtlpProtocol').mockReturnValue('http');
96
+ vi.spyOn(mockConfig, 'getTelemetryOtlpEndpoint').mockReturnValue(
97
+ 'https://my-collector.com',
98
+ );
99
+ initializeTelemetry(mockConfig);
100
+ expect(OTLPTraceExporterHttp).toHaveBeenCalledWith(
101
+ expect.objectContaining({ url: 'https://my-collector.com/' }),
102
+ );
103
+ });
104
+ });
projects/ui/qwen-code/packages/core/src/telemetry/sdk.ts ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { DiagConsoleLogger, DiagLogLevel, diag } from '@opentelemetry/api';
8
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
9
+ import { OTLPLogExporter } from '@opentelemetry/exporter-logs-otlp-grpc';
10
+ import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
11
+ import { OTLPTraceExporter as OTLPTraceExporterHttp } from '@opentelemetry/exporter-trace-otlp-http';
12
+ import { OTLPLogExporter as OTLPLogExporterHttp } from '@opentelemetry/exporter-logs-otlp-http';
13
+ import { OTLPMetricExporter as OTLPMetricExporterHttp } from '@opentelemetry/exporter-metrics-otlp-http';
14
+ import { CompressionAlgorithm } from '@opentelemetry/otlp-exporter-base';
15
+ import { NodeSDK } from '@opentelemetry/sdk-node';
16
+ import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
17
+ import { resourceFromAttributes } from '@opentelemetry/resources';
18
+ import {
19
+ BatchSpanProcessor,
20
+ ConsoleSpanExporter,
21
+ } from '@opentelemetry/sdk-trace-node';
22
+ import {
23
+ BatchLogRecordProcessor,
24
+ ConsoleLogRecordExporter,
25
+ } from '@opentelemetry/sdk-logs';
26
+ import {
27
+ ConsoleMetricExporter,
28
+ PeriodicExportingMetricReader,
29
+ } from '@opentelemetry/sdk-metrics';
30
+ import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
31
+ import { Config } from '../config/config.js';
32
+ import { SERVICE_NAME } from './constants.js';
33
+ import { initializeMetrics } from './metrics.js';
34
+ import {
35
+ FileLogExporter,
36
+ FileMetricExporter,
37
+ FileSpanExporter,
38
+ } from './file-exporters.js';
39
+
40
+ // For troubleshooting, set the log level to DiagLogLevel.DEBUG
41
+ diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO);
42
+
43
+ let sdk: NodeSDK | undefined;
44
+ let telemetryInitialized = false;
45
+
46
+ export function isTelemetrySdkInitialized(): boolean {
47
+ return telemetryInitialized;
48
+ }
49
+
50
+ function parseOtlpEndpoint(
51
+ otlpEndpointSetting: string | undefined,
52
+ protocol: 'grpc' | 'http',
53
+ ): string | undefined {
54
+ if (!otlpEndpointSetting) {
55
+ return undefined;
56
+ }
57
+ // Trim leading/trailing quotes that might come from env variables
58
+ const trimmedEndpoint = otlpEndpointSetting.replace(/^["']|["']$/g, '');
59
+
60
+ try {
61
+ const url = new URL(trimmedEndpoint);
62
+ if (protocol === 'grpc') {
63
+ // OTLP gRPC exporters expect an endpoint in the format scheme://host:port
64
+ // The `origin` property provides this, stripping any path, query, or hash.
65
+ return url.origin;
66
+ }
67
+ // For http, use the full href.
68
+ return url.href;
69
+ } catch (error) {
70
+ diag.error('Invalid OTLP endpoint URL provided:', trimmedEndpoint, error);
71
+ return undefined;
72
+ }
73
+ }
74
+
75
+ export function initializeTelemetry(config: Config): void {
76
+ if (telemetryInitialized || !config.getTelemetryEnabled()) {
77
+ return;
78
+ }
79
+
80
+ const resource = resourceFromAttributes({
81
+ [SemanticResourceAttributes.SERVICE_NAME]: SERVICE_NAME,
82
+ [SemanticResourceAttributes.SERVICE_VERSION]: process.version,
83
+ 'session.id': config.getSessionId(),
84
+ });
85
+
86
+ const otlpEndpoint = config.getTelemetryOtlpEndpoint();
87
+ const otlpProtocol = config.getTelemetryOtlpProtocol();
88
+ const parsedEndpoint = parseOtlpEndpoint(otlpEndpoint, otlpProtocol);
89
+ const useOtlp = !!parsedEndpoint;
90
+ const telemetryOutfile = config.getTelemetryOutfile();
91
+
92
+ let spanExporter:
93
+ | OTLPTraceExporter
94
+ | OTLPTraceExporterHttp
95
+ | FileSpanExporter
96
+ | ConsoleSpanExporter;
97
+ let logExporter:
98
+ | OTLPLogExporter
99
+ | OTLPLogExporterHttp
100
+ | FileLogExporter
101
+ | ConsoleLogRecordExporter;
102
+ let metricReader: PeriodicExportingMetricReader;
103
+
104
+ if (useOtlp) {
105
+ if (otlpProtocol === 'http') {
106
+ spanExporter = new OTLPTraceExporterHttp({
107
+ url: parsedEndpoint,
108
+ });
109
+ logExporter = new OTLPLogExporterHttp({
110
+ url: parsedEndpoint,
111
+ });
112
+ metricReader = new PeriodicExportingMetricReader({
113
+ exporter: new OTLPMetricExporterHttp({
114
+ url: parsedEndpoint,
115
+ }),
116
+ exportIntervalMillis: 10000,
117
+ });
118
+ } else {
119
+ // grpc
120
+ spanExporter = new OTLPTraceExporter({
121
+ url: parsedEndpoint,
122
+ compression: CompressionAlgorithm.GZIP,
123
+ });
124
+ logExporter = new OTLPLogExporter({
125
+ url: parsedEndpoint,
126
+ compression: CompressionAlgorithm.GZIP,
127
+ });
128
+ metricReader = new PeriodicExportingMetricReader({
129
+ exporter: new OTLPMetricExporter({
130
+ url: parsedEndpoint,
131
+ compression: CompressionAlgorithm.GZIP,
132
+ }),
133
+ exportIntervalMillis: 10000,
134
+ });
135
+ }
136
+ } else if (telemetryOutfile) {
137
+ spanExporter = new FileSpanExporter(telemetryOutfile);
138
+ logExporter = new FileLogExporter(telemetryOutfile);
139
+ metricReader = new PeriodicExportingMetricReader({
140
+ exporter: new FileMetricExporter(telemetryOutfile),
141
+ exportIntervalMillis: 10000,
142
+ });
143
+ } else {
144
+ spanExporter = new ConsoleSpanExporter();
145
+ logExporter = new ConsoleLogRecordExporter();
146
+ metricReader = new PeriodicExportingMetricReader({
147
+ exporter: new ConsoleMetricExporter(),
148
+ exportIntervalMillis: 10000,
149
+ });
150
+ }
151
+
152
+ sdk = new NodeSDK({
153
+ resource,
154
+ spanProcessors: [new BatchSpanProcessor(spanExporter)],
155
+ logRecordProcessors: [new BatchLogRecordProcessor(logExporter)],
156
+ metricReader,
157
+ instrumentations: [new HttpInstrumentation()],
158
+ });
159
+
160
+ try {
161
+ sdk.start();
162
+ if (config.getDebugMode()) {
163
+ console.log('OpenTelemetry SDK started successfully.');
164
+ }
165
+ telemetryInitialized = true;
166
+ initializeMetrics(config);
167
+ } catch (error) {
168
+ console.error('Error starting OpenTelemetry SDK:', error);
169
+ }
170
+
171
+ process.on('SIGTERM', () => {
172
+ shutdownTelemetry(config);
173
+ });
174
+ process.on('SIGINT', () => {
175
+ shutdownTelemetry(config);
176
+ });
177
+ }
178
+
179
+ export async function shutdownTelemetry(config: Config): Promise<void> {
180
+ if (!telemetryInitialized || !sdk) {
181
+ return;
182
+ }
183
+ try {
184
+ await sdk.shutdown();
185
+ if (config.getDebugMode()) {
186
+ console.log('OpenTelemetry SDK shut down successfully.');
187
+ }
188
+ } catch (error) {
189
+ console.error('Error shutting down SDK:', error);
190
+ } finally {
191
+ telemetryInitialized = false;
192
+ }
193
+ }
projects/ui/qwen-code/packages/core/src/telemetry/telemetry.test.ts ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {
9
+ initializeTelemetry,
10
+ shutdownTelemetry,
11
+ isTelemetrySdkInitialized,
12
+ } from './sdk.js';
13
+ import { Config } from '../config/config.js';
14
+ import { NodeSDK } from '@opentelemetry/sdk-node';
15
+
16
+ vi.mock('@opentelemetry/sdk-node');
17
+ vi.mock('../config/config.js');
18
+
19
+ describe('telemetry', () => {
20
+ let mockConfig: Config;
21
+ let mockNodeSdk: NodeSDK;
22
+
23
+ beforeEach(() => {
24
+ vi.resetAllMocks();
25
+
26
+ mockConfig = new Config({
27
+ sessionId: 'test-session-id',
28
+ model: 'test-model',
29
+ targetDir: '/test/dir',
30
+ debugMode: false,
31
+ cwd: '/test/dir',
32
+ });
33
+ vi.spyOn(mockConfig, 'getTelemetryEnabled').mockReturnValue(true);
34
+ vi.spyOn(mockConfig, 'getTelemetryOtlpEndpoint').mockReturnValue(
35
+ 'http://localhost:4317',
36
+ );
37
+ vi.spyOn(mockConfig, 'getSessionId').mockReturnValue('test-session-id');
38
+ mockNodeSdk = {
39
+ start: vi.fn(),
40
+ shutdown: vi.fn().mockResolvedValue(undefined),
41
+ } as unknown as NodeSDK;
42
+ vi.mocked(NodeSDK).mockImplementation(() => mockNodeSdk);
43
+ });
44
+
45
+ afterEach(async () => {
46
+ // Ensure we shut down telemetry even if a test fails.
47
+ if (isTelemetrySdkInitialized()) {
48
+ await shutdownTelemetry(mockConfig);
49
+ }
50
+ });
51
+
52
+ it('should initialize the telemetry service', () => {
53
+ initializeTelemetry(mockConfig);
54
+ expect(NodeSDK).toHaveBeenCalled();
55
+ expect(mockNodeSdk.start).toHaveBeenCalled();
56
+ });
57
+
58
+ it('should shutdown the telemetry service', async () => {
59
+ initializeTelemetry(mockConfig);
60
+ await shutdownTelemetry(mockConfig);
61
+
62
+ expect(mockNodeSdk.shutdown).toHaveBeenCalled();
63
+ });
64
+ });
projects/ui/qwen-code/packages/core/src/telemetry/tool-call-decision.ts ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { ToolConfirmationOutcome } from '../tools/tools.js';
8
+
9
+ export enum ToolCallDecision {
10
+ ACCEPT = 'accept',
11
+ REJECT = 'reject',
12
+ MODIFY = 'modify',
13
+ AUTO_ACCEPT = 'auto_accept',
14
+ }
15
+
16
+ export function getDecisionFromOutcome(
17
+ outcome: ToolConfirmationOutcome,
18
+ ): ToolCallDecision {
19
+ switch (outcome) {
20
+ case ToolConfirmationOutcome.ProceedOnce:
21
+ return ToolCallDecision.ACCEPT;
22
+ case ToolConfirmationOutcome.ProceedAlways:
23
+ case ToolConfirmationOutcome.ProceedAlwaysServer:
24
+ case ToolConfirmationOutcome.ProceedAlwaysTool:
25
+ return ToolCallDecision.AUTO_ACCEPT;
26
+ case ToolConfirmationOutcome.ModifyWithEditor:
27
+ return ToolCallDecision.MODIFY;
28
+ case ToolConfirmationOutcome.Cancel:
29
+ default:
30
+ return ToolCallDecision.REJECT;
31
+ }
32
+ }
projects/ui/qwen-code/packages/core/src/telemetry/types.ts ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { GenerateContentResponseUsageMetadata } from '@google/genai';
8
+ import { Config } from '../config/config.js';
9
+ import { CompletedToolCall } from '../core/coreToolScheduler.js';
10
+ import { DiscoveredMCPTool } from '../tools/mcp-tool.js';
11
+ import { FileDiff } from '../tools/tools.js';
12
+ import { AuthType } from '../core/contentGenerator.js';
13
+ import {
14
+ getDecisionFromOutcome,
15
+ ToolCallDecision,
16
+ } from './tool-call-decision.js';
17
+
18
+ export interface BaseTelemetryEvent {
19
+ 'event.name': string;
20
+ /** Current timestamp in ISO 8601 format */
21
+ 'event.timestamp': string;
22
+ }
23
+
24
+ type CommonFields = keyof BaseTelemetryEvent;
25
+
26
+ export class StartSessionEvent implements BaseTelemetryEvent {
27
+ 'event.name': 'cli_config';
28
+ 'event.timestamp': string;
29
+ model: string;
30
+ embedding_model: string;
31
+ sandbox_enabled: boolean;
32
+ core_tools_enabled: string;
33
+ approval_mode: string;
34
+ api_key_enabled: boolean;
35
+ vertex_ai_enabled: boolean;
36
+ debug_enabled: boolean;
37
+ mcp_servers: string;
38
+ telemetry_enabled: boolean;
39
+ telemetry_log_user_prompts_enabled: boolean;
40
+ file_filtering_respect_git_ignore: boolean;
41
+
42
+ constructor(config: Config) {
43
+ const generatorConfig = config.getContentGeneratorConfig();
44
+ const mcpServers = config.getMcpServers();
45
+
46
+ let useGemini = false;
47
+ let useVertex = false;
48
+ if (generatorConfig && generatorConfig.authType) {
49
+ useGemini = generatorConfig.authType === AuthType.USE_GEMINI;
50
+ useVertex = generatorConfig.authType === AuthType.USE_VERTEX_AI;
51
+ }
52
+
53
+ this['event.name'] = 'cli_config';
54
+ this.model = config.getModel();
55
+ this.embedding_model = config.getEmbeddingModel();
56
+ this.sandbox_enabled =
57
+ typeof config.getSandbox() === 'string' || !!config.getSandbox();
58
+ this.core_tools_enabled = (config.getCoreTools() ?? []).join(',');
59
+ this.approval_mode = config.getApprovalMode();
60
+ this.api_key_enabled = useGemini || useVertex;
61
+ this.vertex_ai_enabled = useVertex;
62
+ this.debug_enabled = config.getDebugMode();
63
+ this.mcp_servers = mcpServers ? Object.keys(mcpServers).join(',') : '';
64
+ this.telemetry_enabled = config.getTelemetryEnabled();
65
+ this.telemetry_log_user_prompts_enabled =
66
+ config.getTelemetryLogPromptsEnabled();
67
+ this.file_filtering_respect_git_ignore =
68
+ config.getFileFilteringRespectGitIgnore();
69
+ }
70
+ }
71
+
72
+ export class EndSessionEvent implements BaseTelemetryEvent {
73
+ 'event.name': 'end_session';
74
+ 'event.timestamp': string;
75
+ session_id?: string;
76
+
77
+ constructor(config?: Config) {
78
+ this['event.name'] = 'end_session';
79
+ this['event.timestamp'] = new Date().toISOString();
80
+ this.session_id = config?.getSessionId();
81
+ }
82
+ }
83
+
84
+ export class UserPromptEvent implements BaseTelemetryEvent {
85
+ 'event.name': 'user_prompt';
86
+ 'event.timestamp': string;
87
+ prompt_length: number;
88
+ prompt_id: string;
89
+ auth_type?: string;
90
+ prompt?: string;
91
+
92
+ constructor(
93
+ prompt_length: number,
94
+ prompt_Id: string,
95
+ auth_type?: string,
96
+ prompt?: string,
97
+ ) {
98
+ this['event.name'] = 'user_prompt';
99
+ this['event.timestamp'] = new Date().toISOString();
100
+ this.prompt_length = prompt_length;
101
+ this.prompt_id = prompt_Id;
102
+ this.auth_type = auth_type;
103
+ this.prompt = prompt;
104
+ }
105
+ }
106
+
107
+ export class ToolCallEvent implements BaseTelemetryEvent {
108
+ 'event.name': 'tool_call';
109
+ 'event.timestamp': string;
110
+ function_name: string;
111
+ function_args: Record<string, unknown>;
112
+ duration_ms: number;
113
+ success: boolean;
114
+ decision?: ToolCallDecision;
115
+ error?: string;
116
+ error_type?: string;
117
+ prompt_id: string;
118
+ tool_type: 'native' | 'mcp';
119
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
120
+ metadata?: { [key: string]: any };
121
+
122
+ constructor(call: CompletedToolCall) {
123
+ this['event.name'] = 'tool_call';
124
+ this['event.timestamp'] = new Date().toISOString();
125
+ this.function_name = call.request.name;
126
+ this.function_args = call.request.args;
127
+ this.duration_ms = call.durationMs ?? 0;
128
+ this.success = call.status === 'success';
129
+ this.decision = call.outcome
130
+ ? getDecisionFromOutcome(call.outcome)
131
+ : undefined;
132
+ this.error = call.response.error?.message;
133
+ this.error_type = call.response.errorType;
134
+ this.prompt_id = call.request.prompt_id;
135
+ this.tool_type =
136
+ typeof call.tool !== 'undefined' && call.tool instanceof DiscoveredMCPTool
137
+ ? 'mcp'
138
+ : 'native';
139
+
140
+ if (
141
+ call.status === 'success' &&
142
+ typeof call.response.resultDisplay === 'object' &&
143
+ call.response.resultDisplay !== null &&
144
+ 'diffStat' in call.response.resultDisplay
145
+ ) {
146
+ const diffStat = (call.response.resultDisplay as FileDiff).diffStat;
147
+ if (diffStat) {
148
+ this.metadata = {
149
+ ai_added_lines: diffStat.ai_added_lines,
150
+ ai_removed_lines: diffStat.ai_removed_lines,
151
+ user_added_lines: diffStat.user_added_lines,
152
+ user_removed_lines: diffStat.user_removed_lines,
153
+ };
154
+ }
155
+ }
156
+ }
157
+ }
158
+
159
+ export class ApiRequestEvent implements BaseTelemetryEvent {
160
+ 'event.name': 'api_request';
161
+ 'event.timestamp': string;
162
+ model: string;
163
+ prompt_id: string;
164
+ request_text?: string;
165
+
166
+ constructor(model: string, prompt_id: string, request_text?: string) {
167
+ this['event.name'] = 'api_request';
168
+ this['event.timestamp'] = new Date().toISOString();
169
+ this.model = model;
170
+ this.prompt_id = prompt_id;
171
+ this.request_text = request_text;
172
+ }
173
+ }
174
+
175
+ export class ApiErrorEvent implements BaseTelemetryEvent {
176
+ 'event.name': 'api_error';
177
+ 'event.timestamp': string; // ISO 8601
178
+ response_id?: string;
179
+ model: string;
180
+ error: string;
181
+ error_type?: string;
182
+ status_code?: number | string;
183
+ duration_ms: number;
184
+ prompt_id: string;
185
+ auth_type?: string;
186
+
187
+ constructor(
188
+ response_id: string | undefined,
189
+ model: string,
190
+ error: string,
191
+ duration_ms: number,
192
+ prompt_id: string,
193
+ auth_type?: string,
194
+ error_type?: string,
195
+ status_code?: number | string,
196
+ ) {
197
+ this['event.name'] = 'api_error';
198
+ this['event.timestamp'] = new Date().toISOString();
199
+ this.response_id = response_id;
200
+ this.model = model;
201
+ this.error = error;
202
+ this.error_type = error_type;
203
+ this.status_code = status_code;
204
+ this.duration_ms = duration_ms;
205
+ this.prompt_id = prompt_id;
206
+ this.auth_type = auth_type;
207
+ }
208
+ }
209
+
210
+ export class ApiResponseEvent implements BaseTelemetryEvent {
211
+ 'event.name': 'api_response';
212
+ 'event.timestamp': string; // ISO 8601
213
+ response_id: string;
214
+ model: string;
215
+ status_code?: number | string;
216
+ duration_ms: number;
217
+ error?: string;
218
+ input_token_count: number;
219
+ output_token_count: number;
220
+ cached_content_token_count: number;
221
+ thoughts_token_count: number;
222
+ tool_token_count: number;
223
+ total_token_count: number;
224
+ response_text?: string;
225
+ prompt_id: string;
226
+ auth_type?: string;
227
+
228
+ constructor(
229
+ response_id: string,
230
+ model: string,
231
+ duration_ms: number,
232
+ prompt_id: string,
233
+ auth_type?: string,
234
+ usage_data?: GenerateContentResponseUsageMetadata,
235
+ response_text?: string,
236
+ error?: string,
237
+ ) {
238
+ this['event.name'] = 'api_response';
239
+ this['event.timestamp'] = new Date().toISOString();
240
+ this.response_id = response_id;
241
+ this.model = model;
242
+ this.duration_ms = duration_ms;
243
+ this.status_code = 200;
244
+ this.input_token_count = usage_data?.promptTokenCount ?? 0;
245
+ this.output_token_count = usage_data?.candidatesTokenCount ?? 0;
246
+ this.cached_content_token_count = usage_data?.cachedContentTokenCount ?? 0;
247
+ this.thoughts_token_count = usage_data?.thoughtsTokenCount ?? 0;
248
+ this.tool_token_count = usage_data?.toolUsePromptTokenCount ?? 0;
249
+ this.total_token_count = usage_data?.totalTokenCount ?? 0;
250
+ this.response_text = response_text;
251
+ this.error = error;
252
+ this.prompt_id = prompt_id;
253
+ this.auth_type = auth_type;
254
+ }
255
+ }
256
+
257
+ export class FlashFallbackEvent implements BaseTelemetryEvent {
258
+ 'event.name': 'flash_fallback';
259
+ 'event.timestamp': string;
260
+ auth_type: string;
261
+
262
+ constructor(auth_type: string) {
263
+ this['event.name'] = 'flash_fallback';
264
+ this['event.timestamp'] = new Date().toISOString();
265
+ this.auth_type = auth_type;
266
+ }
267
+ }
268
+
269
+ export enum LoopType {
270
+ CONSECUTIVE_IDENTICAL_TOOL_CALLS = 'consecutive_identical_tool_calls',
271
+ CHANTING_IDENTICAL_SENTENCES = 'chanting_identical_sentences',
272
+ LLM_DETECTED_LOOP = 'llm_detected_loop',
273
+ }
274
+
275
+ export class LoopDetectedEvent implements BaseTelemetryEvent {
276
+ 'event.name': 'loop_detected';
277
+ 'event.timestamp': string;
278
+ loop_type: LoopType;
279
+ prompt_id: string;
280
+
281
+ constructor(loop_type: LoopType, prompt_id: string) {
282
+ this['event.name'] = 'loop_detected';
283
+ this['event.timestamp'] = new Date().toISOString();
284
+ this.loop_type = loop_type;
285
+ this.prompt_id = prompt_id;
286
+ }
287
+ }
288
+
289
+ export class NextSpeakerCheckEvent implements BaseTelemetryEvent {
290
+ 'event.name': 'next_speaker_check';
291
+ 'event.timestamp': string;
292
+ prompt_id: string;
293
+ finish_reason: string;
294
+ result: string;
295
+
296
+ constructor(prompt_id: string, finish_reason: string, result: string) {
297
+ this['event.name'] = 'next_speaker_check';
298
+ this['event.timestamp'] = new Date().toISOString();
299
+ this.prompt_id = prompt_id;
300
+ this.finish_reason = finish_reason;
301
+ this.result = result;
302
+ }
303
+ }
304
+
305
+ export interface SlashCommandEvent extends BaseTelemetryEvent {
306
+ 'event.name': 'slash_command';
307
+ 'event.timestamp': string;
308
+ command: string;
309
+ subcommand?: string;
310
+ status?: SlashCommandStatus;
311
+ }
312
+
313
+ export function makeSlashCommandEvent({
314
+ command,
315
+ subcommand,
316
+ status,
317
+ }: Omit<SlashCommandEvent, CommonFields>): SlashCommandEvent {
318
+ return {
319
+ 'event.name': 'slash_command',
320
+ 'event.timestamp': new Date().toISOString(),
321
+ command,
322
+ subcommand,
323
+ status,
324
+ };
325
+ }
326
+
327
+ export enum SlashCommandStatus {
328
+ SUCCESS = 'success',
329
+ ERROR = 'error',
330
+ }
331
+
332
+ export interface ChatCompressionEvent extends BaseTelemetryEvent {
333
+ 'event.name': 'chat_compression';
334
+ 'event.timestamp': string;
335
+ tokens_before: number;
336
+ tokens_after: number;
337
+ }
338
+
339
+ export function makeChatCompressionEvent({
340
+ tokens_before,
341
+ tokens_after,
342
+ }: Omit<ChatCompressionEvent, CommonFields>): ChatCompressionEvent {
343
+ return {
344
+ 'event.name': 'chat_compression',
345
+ 'event.timestamp': new Date().toISOString(),
346
+ tokens_before,
347
+ tokens_after,
348
+ };
349
+ }
350
+
351
+ export class MalformedJsonResponseEvent implements BaseTelemetryEvent {
352
+ 'event.name': 'malformed_json_response';
353
+ 'event.timestamp': string;
354
+ model: string;
355
+
356
+ constructor(model: string) {
357
+ this['event.name'] = 'malformed_json_response';
358
+ this['event.timestamp'] = new Date().toISOString();
359
+ this.model = model;
360
+ }
361
+ }
362
+
363
+ export enum IdeConnectionType {
364
+ START = 'start',
365
+ SESSION = 'session',
366
+ }
367
+
368
+ export class IdeConnectionEvent {
369
+ 'event.name': 'ide_connection';
370
+ 'event.timestamp': string;
371
+ connection_type: IdeConnectionType;
372
+
373
+ constructor(connection_type: IdeConnectionType) {
374
+ this['event.name'] = 'ide_connection';
375
+ this['event.timestamp'] = new Date().toISOString();
376
+ this.connection_type = connection_type;
377
+ }
378
+ }
379
+
380
+ export class KittySequenceOverflowEvent {
381
+ 'event.name': 'kitty_sequence_overflow';
382
+ 'event.timestamp': string; // ISO 8601
383
+ sequence_length: number;
384
+ truncated_sequence: string;
385
+ constructor(sequence_length: number, truncated_sequence: string) {
386
+ this['event.name'] = 'kitty_sequence_overflow';
387
+ this['event.timestamp'] = new Date().toISOString();
388
+ this.sequence_length = sequence_length;
389
+ // Truncate to first 20 chars for logging (avoid logging sensitive data)
390
+ this.truncated_sequence = truncated_sequence.substring(0, 20);
391
+ }
392
+ }
393
+
394
+ // Add these new event interfaces
395
+ export class InvalidChunkEvent implements BaseTelemetryEvent {
396
+ 'event.name': 'invalid_chunk';
397
+ 'event.timestamp': string;
398
+ error_message?: string; // Optional: validation error details
399
+
400
+ constructor(error_message?: string) {
401
+ this['event.name'] = 'invalid_chunk';
402
+ this['event.timestamp'] = new Date().toISOString();
403
+ this.error_message = error_message;
404
+ }
405
+ }
406
+
407
+ export class ContentRetryEvent implements BaseTelemetryEvent {
408
+ 'event.name': 'content_retry';
409
+ 'event.timestamp': string;
410
+ attempt_number: number;
411
+ error_type: string; // e.g., 'EmptyStreamError'
412
+ retry_delay_ms: number;
413
+
414
+ constructor(
415
+ attempt_number: number,
416
+ error_type: string,
417
+ retry_delay_ms: number,
418
+ ) {
419
+ this['event.name'] = 'content_retry';
420
+ this['event.timestamp'] = new Date().toISOString();
421
+ this.attempt_number = attempt_number;
422
+ this.error_type = error_type;
423
+ this.retry_delay_ms = retry_delay_ms;
424
+ }
425
+ }
426
+
427
+ export class ContentRetryFailureEvent implements BaseTelemetryEvent {
428
+ 'event.name': 'content_retry_failure';
429
+ 'event.timestamp': string;
430
+ total_attempts: number;
431
+ final_error_type: string;
432
+ total_duration_ms?: number; // Optional: total time spent retrying
433
+
434
+ constructor(
435
+ total_attempts: number,
436
+ final_error_type: string,
437
+ total_duration_ms?: number,
438
+ ) {
439
+ this['event.name'] = 'content_retry_failure';
440
+ this['event.timestamp'] = new Date().toISOString();
441
+ this.total_attempts = total_attempts;
442
+ this.final_error_type = final_error_type;
443
+ this.total_duration_ms = total_duration_ms;
444
+ }
445
+ }
446
+
447
+ export type TelemetryEvent =
448
+ | StartSessionEvent
449
+ | EndSessionEvent
450
+ | UserPromptEvent
451
+ | ToolCallEvent
452
+ | ApiRequestEvent
453
+ | ApiErrorEvent
454
+ | ApiResponseEvent
455
+ | FlashFallbackEvent
456
+ | LoopDetectedEvent
457
+ | NextSpeakerCheckEvent
458
+ | KittySequenceOverflowEvent
459
+ | MalformedJsonResponseEvent
460
+ | IdeConnectionEvent
461
+ | SlashCommandEvent
462
+ | InvalidChunkEvent
463
+ | ContentRetryEvent
464
+ | ContentRetryFailureEvent;
projects/ui/qwen-code/packages/core/src/telemetry/uiTelemetry.test.ts ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
8
+ import { UiTelemetryService } from './uiTelemetry.js';
9
+ import { ToolCallDecision } from './tool-call-decision.js';
10
+ import { ApiErrorEvent, ApiResponseEvent, ToolCallEvent } from './types.js';
11
+ import {
12
+ EVENT_API_ERROR,
13
+ EVENT_API_RESPONSE,
14
+ EVENT_TOOL_CALL,
15
+ } from './constants.js';
16
+ import {
17
+ CompletedToolCall,
18
+ ErroredToolCall,
19
+ SuccessfulToolCall,
20
+ } from '../core/coreToolScheduler.js';
21
+ import { ToolErrorType } from '../tools/tool-error.js';
22
+ import { ToolConfirmationOutcome } from '../tools/tools.js';
23
+ import { MockTool } from '../test-utils/tools.js';
24
+
25
+ const createFakeCompletedToolCall = (
26
+ name: string,
27
+ success: boolean,
28
+ duration = 100,
29
+ outcome?: ToolConfirmationOutcome,
30
+ error?: Error,
31
+ ): CompletedToolCall => {
32
+ const request = {
33
+ callId: `call_${name}_${Date.now()}`,
34
+ name,
35
+ args: { foo: 'bar' },
36
+ isClientInitiated: false,
37
+ prompt_id: 'prompt-id-1',
38
+ };
39
+ const tool = new MockTool(name);
40
+
41
+ if (success) {
42
+ return {
43
+ status: 'success',
44
+ request,
45
+ tool,
46
+ invocation: tool.build({ param: 'test' }),
47
+ response: {
48
+ callId: request.callId,
49
+ responseParts: {
50
+ functionResponse: {
51
+ id: request.callId,
52
+ name,
53
+ response: { output: 'Success!' },
54
+ },
55
+ },
56
+ error: undefined,
57
+ errorType: undefined,
58
+ resultDisplay: 'Success!',
59
+ },
60
+ durationMs: duration,
61
+ outcome,
62
+ } as SuccessfulToolCall;
63
+ } else {
64
+ return {
65
+ status: 'error',
66
+ request,
67
+ tool,
68
+ response: {
69
+ callId: request.callId,
70
+ responseParts: {
71
+ functionResponse: {
72
+ id: request.callId,
73
+ name,
74
+ response: { error: 'Tool failed' },
75
+ },
76
+ },
77
+ error: error || new Error('Tool failed'),
78
+ errorType: ToolErrorType.UNKNOWN,
79
+ resultDisplay: 'Failure!',
80
+ },
81
+ durationMs: duration,
82
+ outcome,
83
+ } as ErroredToolCall;
84
+ }
85
+ };
86
+
87
+ describe('UiTelemetryService', () => {
88
+ let service: UiTelemetryService;
89
+
90
+ beforeEach(() => {
91
+ service = new UiTelemetryService();
92
+ });
93
+
94
+ it('should have correct initial metrics', () => {
95
+ const metrics = service.getMetrics();
96
+ expect(metrics).toEqual({
97
+ models: {},
98
+ tools: {
99
+ totalCalls: 0,
100
+ totalSuccess: 0,
101
+ totalFail: 0,
102
+ totalDurationMs: 0,
103
+ totalDecisions: {
104
+ [ToolCallDecision.ACCEPT]: 0,
105
+ [ToolCallDecision.REJECT]: 0,
106
+ [ToolCallDecision.MODIFY]: 0,
107
+ [ToolCallDecision.AUTO_ACCEPT]: 0,
108
+ },
109
+ byName: {},
110
+ },
111
+ files: {
112
+ totalLinesAdded: 0,
113
+ totalLinesRemoved: 0,
114
+ },
115
+ });
116
+ expect(service.getLastPromptTokenCount()).toBe(0);
117
+ });
118
+
119
+ it('should emit an update event when an event is added', () => {
120
+ const spy = vi.fn();
121
+ service.on('update', spy);
122
+
123
+ const event = {
124
+ 'event.name': EVENT_API_RESPONSE,
125
+ model: 'gemini-2.5-pro',
126
+ duration_ms: 500,
127
+ input_token_count: 10,
128
+ output_token_count: 20,
129
+ total_token_count: 30,
130
+ cached_content_token_count: 5,
131
+ thoughts_token_count: 2,
132
+ tool_token_count: 3,
133
+ } as ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE };
134
+
135
+ service.addEvent(event);
136
+
137
+ expect(spy).toHaveBeenCalledOnce();
138
+ const { metrics, lastPromptTokenCount } = spy.mock.calls[0][0];
139
+ expect(metrics).toBeDefined();
140
+ expect(lastPromptTokenCount).toBe(10);
141
+ });
142
+
143
+ describe('API Response Event Processing', () => {
144
+ it('should process a single ApiResponseEvent', () => {
145
+ const event = {
146
+ 'event.name': EVENT_API_RESPONSE,
147
+ model: 'gemini-2.5-pro',
148
+ duration_ms: 500,
149
+ input_token_count: 10,
150
+ output_token_count: 20,
151
+ total_token_count: 30,
152
+ cached_content_token_count: 5,
153
+ thoughts_token_count: 2,
154
+ tool_token_count: 3,
155
+ } as ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE };
156
+
157
+ service.addEvent(event);
158
+
159
+ const metrics = service.getMetrics();
160
+ expect(metrics.models['gemini-2.5-pro']).toEqual({
161
+ api: {
162
+ totalRequests: 1,
163
+ totalErrors: 0,
164
+ totalLatencyMs: 500,
165
+ },
166
+ tokens: {
167
+ prompt: 10,
168
+ candidates: 20,
169
+ total: 30,
170
+ cached: 5,
171
+ thoughts: 2,
172
+ tool: 3,
173
+ },
174
+ });
175
+ expect(service.getLastPromptTokenCount()).toBe(10);
176
+ });
177
+
178
+ it('should aggregate multiple ApiResponseEvents for the same model', () => {
179
+ const event1 = {
180
+ 'event.name': EVENT_API_RESPONSE,
181
+ model: 'gemini-2.5-pro',
182
+ duration_ms: 500,
183
+ input_token_count: 10,
184
+ output_token_count: 20,
185
+ total_token_count: 30,
186
+ cached_content_token_count: 5,
187
+ thoughts_token_count: 2,
188
+ tool_token_count: 3,
189
+ } as ApiResponseEvent & {
190
+ 'event.name': typeof EVENT_API_RESPONSE;
191
+ };
192
+ const event2 = {
193
+ 'event.name': EVENT_API_RESPONSE,
194
+ model: 'gemini-2.5-pro',
195
+ duration_ms: 600,
196
+ input_token_count: 15,
197
+ output_token_count: 25,
198
+ total_token_count: 40,
199
+ cached_content_token_count: 10,
200
+ thoughts_token_count: 4,
201
+ tool_token_count: 6,
202
+ } as ApiResponseEvent & {
203
+ 'event.name': typeof EVENT_API_RESPONSE;
204
+ };
205
+
206
+ service.addEvent(event1);
207
+ service.addEvent(event2);
208
+
209
+ const metrics = service.getMetrics();
210
+ expect(metrics.models['gemini-2.5-pro']).toEqual({
211
+ api: {
212
+ totalRequests: 2,
213
+ totalErrors: 0,
214
+ totalLatencyMs: 1100,
215
+ },
216
+ tokens: {
217
+ prompt: 25,
218
+ candidates: 45,
219
+ total: 70,
220
+ cached: 15,
221
+ thoughts: 6,
222
+ tool: 9,
223
+ },
224
+ });
225
+ expect(service.getLastPromptTokenCount()).toBe(15);
226
+ });
227
+
228
+ it('should handle ApiResponseEvents for different models', () => {
229
+ const event1 = {
230
+ 'event.name': EVENT_API_RESPONSE,
231
+ model: 'gemini-2.5-pro',
232
+ duration_ms: 500,
233
+ input_token_count: 10,
234
+ output_token_count: 20,
235
+ total_token_count: 30,
236
+ cached_content_token_count: 5,
237
+ thoughts_token_count: 2,
238
+ tool_token_count: 3,
239
+ } as ApiResponseEvent & {
240
+ 'event.name': typeof EVENT_API_RESPONSE;
241
+ };
242
+ const event2 = {
243
+ 'event.name': EVENT_API_RESPONSE,
244
+ model: 'gemini-2.5-flash',
245
+ duration_ms: 1000,
246
+ input_token_count: 100,
247
+ output_token_count: 200,
248
+ total_token_count: 300,
249
+ cached_content_token_count: 50,
250
+ thoughts_token_count: 20,
251
+ tool_token_count: 30,
252
+ } as ApiResponseEvent & {
253
+ 'event.name': typeof EVENT_API_RESPONSE;
254
+ };
255
+
256
+ service.addEvent(event1);
257
+ service.addEvent(event2);
258
+
259
+ const metrics = service.getMetrics();
260
+ expect(metrics.models['gemini-2.5-pro']).toBeDefined();
261
+ expect(metrics.models['gemini-2.5-flash']).toBeDefined();
262
+ expect(metrics.models['gemini-2.5-pro'].api.totalRequests).toBe(1);
263
+ expect(metrics.models['gemini-2.5-flash'].api.totalRequests).toBe(1);
264
+ expect(service.getLastPromptTokenCount()).toBe(100);
265
+ });
266
+ });
267
+
268
+ describe('API Error Event Processing', () => {
269
+ it('should process a single ApiErrorEvent', () => {
270
+ const event = {
271
+ 'event.name': EVENT_API_ERROR,
272
+ model: 'gemini-2.5-pro',
273
+ duration_ms: 300,
274
+ error: 'Something went wrong',
275
+ } as ApiErrorEvent & { 'event.name': typeof EVENT_API_ERROR };
276
+
277
+ service.addEvent(event);
278
+
279
+ const metrics = service.getMetrics();
280
+ expect(metrics.models['gemini-2.5-pro']).toEqual({
281
+ api: {
282
+ totalRequests: 1,
283
+ totalErrors: 1,
284
+ totalLatencyMs: 300,
285
+ },
286
+ tokens: {
287
+ prompt: 0,
288
+ candidates: 0,
289
+ total: 0,
290
+ cached: 0,
291
+ thoughts: 0,
292
+ tool: 0,
293
+ },
294
+ });
295
+ });
296
+
297
+ it('should aggregate ApiErrorEvents and ApiResponseEvents', () => {
298
+ const responseEvent = {
299
+ 'event.name': EVENT_API_RESPONSE,
300
+ model: 'gemini-2.5-pro',
301
+ duration_ms: 500,
302
+ input_token_count: 10,
303
+ output_token_count: 20,
304
+ total_token_count: 30,
305
+ cached_content_token_count: 5,
306
+ thoughts_token_count: 2,
307
+ tool_token_count: 3,
308
+ } as ApiResponseEvent & {
309
+ 'event.name': typeof EVENT_API_RESPONSE;
310
+ };
311
+ const errorEvent = {
312
+ 'event.name': EVENT_API_ERROR,
313
+ model: 'gemini-2.5-pro',
314
+ duration_ms: 300,
315
+ error: 'Something went wrong',
316
+ } as ApiErrorEvent & { 'event.name': typeof EVENT_API_ERROR };
317
+
318
+ service.addEvent(responseEvent);
319
+ service.addEvent(errorEvent);
320
+
321
+ const metrics = service.getMetrics();
322
+ expect(metrics.models['gemini-2.5-pro']).toEqual({
323
+ api: {
324
+ totalRequests: 2,
325
+ totalErrors: 1,
326
+ totalLatencyMs: 800,
327
+ },
328
+ tokens: {
329
+ prompt: 10,
330
+ candidates: 20,
331
+ total: 30,
332
+ cached: 5,
333
+ thoughts: 2,
334
+ tool: 3,
335
+ },
336
+ });
337
+ });
338
+ });
339
+
340
+ describe('Tool Call Event Processing', () => {
341
+ it('should process a single successful ToolCallEvent', () => {
342
+ const toolCall = createFakeCompletedToolCall(
343
+ 'test_tool',
344
+ true,
345
+ 150,
346
+ ToolConfirmationOutcome.ProceedOnce,
347
+ );
348
+ service.addEvent({
349
+ ...structuredClone(new ToolCallEvent(toolCall)),
350
+ 'event.name': EVENT_TOOL_CALL,
351
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
352
+
353
+ const metrics = service.getMetrics();
354
+ const { tools } = metrics;
355
+
356
+ expect(tools.totalCalls).toBe(1);
357
+ expect(tools.totalSuccess).toBe(1);
358
+ expect(tools.totalFail).toBe(0);
359
+ expect(tools.totalDurationMs).toBe(150);
360
+ expect(tools.totalDecisions[ToolCallDecision.ACCEPT]).toBe(1);
361
+ expect(tools.byName['test_tool']).toEqual({
362
+ count: 1,
363
+ success: 1,
364
+ fail: 0,
365
+ durationMs: 150,
366
+ decisions: {
367
+ [ToolCallDecision.ACCEPT]: 1,
368
+ [ToolCallDecision.REJECT]: 0,
369
+ [ToolCallDecision.MODIFY]: 0,
370
+ [ToolCallDecision.AUTO_ACCEPT]: 0,
371
+ },
372
+ });
373
+ });
374
+
375
+ it('should process a single failed ToolCallEvent', () => {
376
+ const toolCall = createFakeCompletedToolCall(
377
+ 'test_tool',
378
+ false,
379
+ 200,
380
+ ToolConfirmationOutcome.Cancel,
381
+ );
382
+ service.addEvent({
383
+ ...structuredClone(new ToolCallEvent(toolCall)),
384
+ 'event.name': EVENT_TOOL_CALL,
385
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
386
+
387
+ const metrics = service.getMetrics();
388
+ const { tools } = metrics;
389
+
390
+ expect(tools.totalCalls).toBe(1);
391
+ expect(tools.totalSuccess).toBe(0);
392
+ expect(tools.totalFail).toBe(1);
393
+ expect(tools.totalDurationMs).toBe(200);
394
+ expect(tools.totalDecisions[ToolCallDecision.REJECT]).toBe(1);
395
+ expect(tools.byName['test_tool']).toEqual({
396
+ count: 1,
397
+ success: 0,
398
+ fail: 1,
399
+ durationMs: 200,
400
+ decisions: {
401
+ [ToolCallDecision.ACCEPT]: 0,
402
+ [ToolCallDecision.REJECT]: 1,
403
+ [ToolCallDecision.MODIFY]: 0,
404
+ [ToolCallDecision.AUTO_ACCEPT]: 0,
405
+ },
406
+ });
407
+ });
408
+
409
+ it('should process a ToolCallEvent with modify decision', () => {
410
+ const toolCall = createFakeCompletedToolCall(
411
+ 'test_tool',
412
+ true,
413
+ 250,
414
+ ToolConfirmationOutcome.ModifyWithEditor,
415
+ );
416
+ service.addEvent({
417
+ ...structuredClone(new ToolCallEvent(toolCall)),
418
+ 'event.name': EVENT_TOOL_CALL,
419
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
420
+
421
+ const metrics = service.getMetrics();
422
+ const { tools } = metrics;
423
+
424
+ expect(tools.totalDecisions[ToolCallDecision.MODIFY]).toBe(1);
425
+ expect(tools.byName['test_tool'].decisions[ToolCallDecision.MODIFY]).toBe(
426
+ 1,
427
+ );
428
+ });
429
+
430
+ it('should process a ToolCallEvent without a decision', () => {
431
+ const toolCall = createFakeCompletedToolCall('test_tool', true, 100);
432
+ service.addEvent({
433
+ ...structuredClone(new ToolCallEvent(toolCall)),
434
+ 'event.name': EVENT_TOOL_CALL,
435
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
436
+
437
+ const metrics = service.getMetrics();
438
+ const { tools } = metrics;
439
+
440
+ expect(tools.totalDecisions).toEqual({
441
+ [ToolCallDecision.ACCEPT]: 0,
442
+ [ToolCallDecision.REJECT]: 0,
443
+ [ToolCallDecision.MODIFY]: 0,
444
+ [ToolCallDecision.AUTO_ACCEPT]: 0,
445
+ });
446
+ expect(tools.byName['test_tool'].decisions).toEqual({
447
+ [ToolCallDecision.ACCEPT]: 0,
448
+ [ToolCallDecision.REJECT]: 0,
449
+ [ToolCallDecision.MODIFY]: 0,
450
+ [ToolCallDecision.AUTO_ACCEPT]: 0,
451
+ });
452
+ });
453
+
454
+ it('should aggregate multiple ToolCallEvents for the same tool', () => {
455
+ const toolCall1 = createFakeCompletedToolCall(
456
+ 'test_tool',
457
+ true,
458
+ 100,
459
+ ToolConfirmationOutcome.ProceedOnce,
460
+ );
461
+ const toolCall2 = createFakeCompletedToolCall(
462
+ 'test_tool',
463
+ false,
464
+ 150,
465
+ ToolConfirmationOutcome.Cancel,
466
+ );
467
+
468
+ service.addEvent({
469
+ ...structuredClone(new ToolCallEvent(toolCall1)),
470
+ 'event.name': EVENT_TOOL_CALL,
471
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
472
+ service.addEvent({
473
+ ...structuredClone(new ToolCallEvent(toolCall2)),
474
+ 'event.name': EVENT_TOOL_CALL,
475
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
476
+
477
+ const metrics = service.getMetrics();
478
+ const { tools } = metrics;
479
+
480
+ expect(tools.totalCalls).toBe(2);
481
+ expect(tools.totalSuccess).toBe(1);
482
+ expect(tools.totalFail).toBe(1);
483
+ expect(tools.totalDurationMs).toBe(250);
484
+ expect(tools.totalDecisions[ToolCallDecision.ACCEPT]).toBe(1);
485
+ expect(tools.totalDecisions[ToolCallDecision.REJECT]).toBe(1);
486
+ expect(tools.byName['test_tool']).toEqual({
487
+ count: 2,
488
+ success: 1,
489
+ fail: 1,
490
+ durationMs: 250,
491
+ decisions: {
492
+ [ToolCallDecision.ACCEPT]: 1,
493
+ [ToolCallDecision.REJECT]: 1,
494
+ [ToolCallDecision.MODIFY]: 0,
495
+ [ToolCallDecision.AUTO_ACCEPT]: 0,
496
+ },
497
+ });
498
+ });
499
+
500
+ it('should handle ToolCallEvents for different tools', () => {
501
+ const toolCall1 = createFakeCompletedToolCall('tool_A', true, 100);
502
+ const toolCall2 = createFakeCompletedToolCall('tool_B', false, 200);
503
+ service.addEvent({
504
+ ...structuredClone(new ToolCallEvent(toolCall1)),
505
+ 'event.name': EVENT_TOOL_CALL,
506
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
507
+ service.addEvent({
508
+ ...structuredClone(new ToolCallEvent(toolCall2)),
509
+ 'event.name': EVENT_TOOL_CALL,
510
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
511
+
512
+ const metrics = service.getMetrics();
513
+ const { tools } = metrics;
514
+
515
+ expect(tools.totalCalls).toBe(2);
516
+ expect(tools.totalSuccess).toBe(1);
517
+ expect(tools.totalFail).toBe(1);
518
+ expect(tools.byName['tool_A']).toBeDefined();
519
+ expect(tools.byName['tool_B']).toBeDefined();
520
+ expect(tools.byName['tool_A'].count).toBe(1);
521
+ expect(tools.byName['tool_B'].count).toBe(1);
522
+ });
523
+ });
524
+
525
+ describe('resetLastPromptTokenCount', () => {
526
+ it('should reset the last prompt token count to 0', () => {
527
+ // First, set up some initial token count
528
+ const event = {
529
+ 'event.name': EVENT_API_RESPONSE,
530
+ model: 'gemini-2.5-pro',
531
+ duration_ms: 500,
532
+ input_token_count: 100,
533
+ output_token_count: 200,
534
+ total_token_count: 300,
535
+ cached_content_token_count: 50,
536
+ thoughts_token_count: 20,
537
+ tool_token_count: 30,
538
+ } as ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE };
539
+
540
+ service.addEvent(event);
541
+ expect(service.getLastPromptTokenCount()).toBe(100);
542
+
543
+ // Now reset the token count
544
+ service.resetLastPromptTokenCount();
545
+ expect(service.getLastPromptTokenCount()).toBe(0);
546
+ });
547
+
548
+ it('should emit an update event when resetLastPromptTokenCount is called', () => {
549
+ const spy = vi.fn();
550
+ service.on('update', spy);
551
+
552
+ // Set up initial token count
553
+ const event = {
554
+ 'event.name': EVENT_API_RESPONSE,
555
+ model: 'gemini-2.5-pro',
556
+ duration_ms: 500,
557
+ input_token_count: 100,
558
+ output_token_count: 200,
559
+ total_token_count: 300,
560
+ cached_content_token_count: 50,
561
+ thoughts_token_count: 20,
562
+ tool_token_count: 30,
563
+ } as ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE };
564
+
565
+ service.addEvent(event);
566
+ spy.mockClear(); // Clear the spy to focus on the reset call
567
+
568
+ service.resetLastPromptTokenCount();
569
+
570
+ expect(spy).toHaveBeenCalledOnce();
571
+ const { metrics, lastPromptTokenCount } = spy.mock.calls[0][0];
572
+ expect(metrics).toBeDefined();
573
+ expect(lastPromptTokenCount).toBe(0);
574
+ });
575
+
576
+ it('should not affect other metrics when resetLastPromptTokenCount is called', () => {
577
+ // Set up initial state with some metrics
578
+ const event = {
579
+ 'event.name': EVENT_API_RESPONSE,
580
+ model: 'gemini-2.5-pro',
581
+ duration_ms: 500,
582
+ input_token_count: 100,
583
+ output_token_count: 200,
584
+ total_token_count: 300,
585
+ cached_content_token_count: 50,
586
+ thoughts_token_count: 20,
587
+ tool_token_count: 30,
588
+ } as ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE };
589
+
590
+ service.addEvent(event);
591
+
592
+ const metricsBefore = service.getMetrics();
593
+
594
+ service.resetLastPromptTokenCount();
595
+
596
+ const metricsAfter = service.getMetrics();
597
+
598
+ // Metrics should be unchanged
599
+ expect(metricsAfter).toEqual(metricsBefore);
600
+
601
+ // Only the last prompt token count should be reset
602
+ expect(service.getLastPromptTokenCount()).toBe(0);
603
+ });
604
+
605
+ it('should work correctly when called multiple times', () => {
606
+ const spy = vi.fn();
607
+ service.on('update', spy);
608
+
609
+ // Set up initial token count
610
+ const event = {
611
+ 'event.name': EVENT_API_RESPONSE,
612
+ model: 'gemini-2.5-pro',
613
+ duration_ms: 500,
614
+ input_token_count: 100,
615
+ output_token_count: 200,
616
+ total_token_count: 300,
617
+ cached_content_token_count: 50,
618
+ thoughts_token_count: 20,
619
+ tool_token_count: 30,
620
+ } as ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE };
621
+
622
+ service.addEvent(event);
623
+ expect(service.getLastPromptTokenCount()).toBe(100);
624
+
625
+ // Reset once
626
+ service.resetLastPromptTokenCount();
627
+ expect(service.getLastPromptTokenCount()).toBe(0);
628
+
629
+ // Reset again - should still be 0 and still emit event
630
+ spy.mockClear();
631
+ service.resetLastPromptTokenCount();
632
+ expect(service.getLastPromptTokenCount()).toBe(0);
633
+ expect(spy).toHaveBeenCalledOnce();
634
+ });
635
+ });
636
+
637
+ describe('Tool Call Event with Line Count Metadata', () => {
638
+ it('should aggregate valid line count metadata', () => {
639
+ const toolCall = createFakeCompletedToolCall('test_tool', true, 100);
640
+ const event = {
641
+ ...structuredClone(new ToolCallEvent(toolCall)),
642
+ 'event.name': EVENT_TOOL_CALL,
643
+ metadata: {
644
+ ai_added_lines: 10,
645
+ ai_removed_lines: 5,
646
+ },
647
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL };
648
+
649
+ service.addEvent(event);
650
+
651
+ const metrics = service.getMetrics();
652
+ expect(metrics.files.totalLinesAdded).toBe(10);
653
+ expect(metrics.files.totalLinesRemoved).toBe(5);
654
+ });
655
+
656
+ it('should ignore null/undefined values in line count metadata', () => {
657
+ const toolCall = createFakeCompletedToolCall('test_tool', true, 100);
658
+ const event = {
659
+ ...structuredClone(new ToolCallEvent(toolCall)),
660
+ 'event.name': EVENT_TOOL_CALL,
661
+ metadata: {
662
+ ai_added_lines: null,
663
+ ai_removed_lines: undefined,
664
+ },
665
+ } as ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL };
666
+
667
+ service.addEvent(event);
668
+
669
+ const metrics = service.getMetrics();
670
+ expect(metrics.files.totalLinesAdded).toBe(0);
671
+ expect(metrics.files.totalLinesRemoved).toBe(0);
672
+ });
673
+ });
674
+ });
projects/ui/qwen-code/packages/core/src/telemetry/uiTelemetry.ts ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { EventEmitter } from 'events';
8
+ import {
9
+ EVENT_API_ERROR,
10
+ EVENT_API_RESPONSE,
11
+ EVENT_TOOL_CALL,
12
+ } from './constants.js';
13
+
14
+ import { ToolCallDecision } from './tool-call-decision.js';
15
+ import { ApiErrorEvent, ApiResponseEvent, ToolCallEvent } from './types.js';
16
+
17
+ export type UiEvent =
18
+ | (ApiResponseEvent & { 'event.name': typeof EVENT_API_RESPONSE })
19
+ | (ApiErrorEvent & { 'event.name': typeof EVENT_API_ERROR })
20
+ | (ToolCallEvent & { 'event.name': typeof EVENT_TOOL_CALL });
21
+
22
+ export interface ToolCallStats {
23
+ count: number;
24
+ success: number;
25
+ fail: number;
26
+ durationMs: number;
27
+ decisions: {
28
+ [ToolCallDecision.ACCEPT]: number;
29
+ [ToolCallDecision.REJECT]: number;
30
+ [ToolCallDecision.MODIFY]: number;
31
+ [ToolCallDecision.AUTO_ACCEPT]: number;
32
+ };
33
+ }
34
+
35
+ export interface ModelMetrics {
36
+ api: {
37
+ totalRequests: number;
38
+ totalErrors: number;
39
+ totalLatencyMs: number;
40
+ };
41
+ tokens: {
42
+ prompt: number;
43
+ candidates: number;
44
+ total: number;
45
+ cached: number;
46
+ thoughts: number;
47
+ tool: number;
48
+ };
49
+ }
50
+
51
+ export interface SessionMetrics {
52
+ models: Record<string, ModelMetrics>;
53
+ tools: {
54
+ totalCalls: number;
55
+ totalSuccess: number;
56
+ totalFail: number;
57
+ totalDurationMs: number;
58
+ totalDecisions: {
59
+ [ToolCallDecision.ACCEPT]: number;
60
+ [ToolCallDecision.REJECT]: number;
61
+ [ToolCallDecision.MODIFY]: number;
62
+ [ToolCallDecision.AUTO_ACCEPT]: number;
63
+ };
64
+ byName: Record<string, ToolCallStats>;
65
+ };
66
+ files: {
67
+ totalLinesAdded: number;
68
+ totalLinesRemoved: number;
69
+ };
70
+ }
71
+
72
+ const createInitialModelMetrics = (): ModelMetrics => ({
73
+ api: {
74
+ totalRequests: 0,
75
+ totalErrors: 0,
76
+ totalLatencyMs: 0,
77
+ },
78
+ tokens: {
79
+ prompt: 0,
80
+ candidates: 0,
81
+ total: 0,
82
+ cached: 0,
83
+ thoughts: 0,
84
+ tool: 0,
85
+ },
86
+ });
87
+
88
+ const createInitialMetrics = (): SessionMetrics => ({
89
+ models: {},
90
+ tools: {
91
+ totalCalls: 0,
92
+ totalSuccess: 0,
93
+ totalFail: 0,
94
+ totalDurationMs: 0,
95
+ totalDecisions: {
96
+ [ToolCallDecision.ACCEPT]: 0,
97
+ [ToolCallDecision.REJECT]: 0,
98
+ [ToolCallDecision.MODIFY]: 0,
99
+ [ToolCallDecision.AUTO_ACCEPT]: 0,
100
+ },
101
+ byName: {},
102
+ },
103
+ files: {
104
+ totalLinesAdded: 0,
105
+ totalLinesRemoved: 0,
106
+ },
107
+ });
108
+
109
+ export class UiTelemetryService extends EventEmitter {
110
+ #metrics: SessionMetrics = createInitialMetrics();
111
+ #lastPromptTokenCount = 0;
112
+
113
+ addEvent(event: UiEvent) {
114
+ switch (event['event.name']) {
115
+ case EVENT_API_RESPONSE:
116
+ this.processApiResponse(event);
117
+ break;
118
+ case EVENT_API_ERROR:
119
+ this.processApiError(event);
120
+ break;
121
+ case EVENT_TOOL_CALL:
122
+ this.processToolCall(event);
123
+ break;
124
+ default:
125
+ // We should not emit update for any other event metric.
126
+ return;
127
+ }
128
+
129
+ this.emit('update', {
130
+ metrics: this.#metrics,
131
+ lastPromptTokenCount: this.#lastPromptTokenCount,
132
+ });
133
+ }
134
+
135
+ getMetrics(): SessionMetrics {
136
+ return this.#metrics;
137
+ }
138
+
139
+ getLastPromptTokenCount(): number {
140
+ return this.#lastPromptTokenCount;
141
+ }
142
+
143
+ resetLastPromptTokenCount(): void {
144
+ this.#lastPromptTokenCount = 0;
145
+ this.emit('update', {
146
+ metrics: this.#metrics,
147
+ lastPromptTokenCount: this.#lastPromptTokenCount,
148
+ });
149
+ }
150
+
151
+ private getOrCreateModelMetrics(modelName: string): ModelMetrics {
152
+ if (!this.#metrics.models[modelName]) {
153
+ this.#metrics.models[modelName] = createInitialModelMetrics();
154
+ }
155
+ return this.#metrics.models[modelName];
156
+ }
157
+
158
+ private processApiResponse(event: ApiResponseEvent) {
159
+ const modelMetrics = this.getOrCreateModelMetrics(event.model);
160
+
161
+ modelMetrics.api.totalRequests++;
162
+ modelMetrics.api.totalLatencyMs += event.duration_ms;
163
+
164
+ modelMetrics.tokens.prompt += event.input_token_count;
165
+ modelMetrics.tokens.candidates += event.output_token_count;
166
+ modelMetrics.tokens.total += event.total_token_count;
167
+ modelMetrics.tokens.cached += event.cached_content_token_count;
168
+ modelMetrics.tokens.thoughts += event.thoughts_token_count;
169
+ modelMetrics.tokens.tool += event.tool_token_count;
170
+
171
+ this.#lastPromptTokenCount = event.input_token_count;
172
+ }
173
+
174
+ private processApiError(event: ApiErrorEvent) {
175
+ const modelMetrics = this.getOrCreateModelMetrics(event.model);
176
+ modelMetrics.api.totalRequests++;
177
+ modelMetrics.api.totalErrors++;
178
+ modelMetrics.api.totalLatencyMs += event.duration_ms;
179
+ }
180
+
181
+ private processToolCall(event: ToolCallEvent) {
182
+ const { tools, files } = this.#metrics;
183
+ tools.totalCalls++;
184
+ tools.totalDurationMs += event.duration_ms;
185
+
186
+ if (event.success) {
187
+ tools.totalSuccess++;
188
+ } else {
189
+ tools.totalFail++;
190
+ }
191
+
192
+ if (!tools.byName[event.function_name]) {
193
+ tools.byName[event.function_name] = {
194
+ count: 0,
195
+ success: 0,
196
+ fail: 0,
197
+ durationMs: 0,
198
+ decisions: {
199
+ [ToolCallDecision.ACCEPT]: 0,
200
+ [ToolCallDecision.REJECT]: 0,
201
+ [ToolCallDecision.MODIFY]: 0,
202
+ [ToolCallDecision.AUTO_ACCEPT]: 0,
203
+ },
204
+ };
205
+ }
206
+
207
+ const toolStats = tools.byName[event.function_name];
208
+ toolStats.count++;
209
+ toolStats.durationMs += event.duration_ms;
210
+ if (event.success) {
211
+ toolStats.success++;
212
+ } else {
213
+ toolStats.fail++;
214
+ }
215
+
216
+ if (event.decision) {
217
+ tools.totalDecisions[event.decision]++;
218
+ toolStats.decisions[event.decision]++;
219
+ }
220
+
221
+ // Aggregate line count data from metadata
222
+ if (event.metadata) {
223
+ if (event.metadata['ai_added_lines'] !== undefined) {
224
+ files.totalLinesAdded += event.metadata['ai_added_lines'];
225
+ }
226
+ if (event.metadata['ai_removed_lines'] !== undefined) {
227
+ files.totalLinesRemoved += event.metadata['ai_removed_lines'];
228
+ }
229
+ }
230
+ }
231
+ }
232
+
233
+ export const uiTelemetryService = new UiTelemetryService();
projects/ui/qwen-code/packages/core/src/test-utils/config.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Config, ConfigParameters } from '../config/config.js';
8
+
9
+ /**
10
+ * Default parameters used for {@link FAKE_CONFIG}
11
+ */
12
+ export const DEFAULT_CONFIG_PARAMETERS: ConfigParameters = {
13
+ usageStatisticsEnabled: true,
14
+ debugMode: false,
15
+ sessionId: 'test-session-id',
16
+ proxy: undefined,
17
+ model: 'gemini-9001-super-duper',
18
+ targetDir: '/',
19
+ cwd: '/',
20
+ };
21
+
22
+ /**
23
+ * Produces a config. Default paramters are set to
24
+ * {@link DEFAULT_CONFIG_PARAMETERS}, optionally, fields can be specified to
25
+ * override those defaults.
26
+ */
27
+ export function makeFakeConfig(
28
+ config: Partial<ConfigParameters> = {
29
+ ...DEFAULT_CONFIG_PARAMETERS,
30
+ },
31
+ ): Config {
32
+ return new Config({
33
+ ...DEFAULT_CONFIG_PARAMETERS,
34
+ ...config,
35
+ });
36
+ }
projects/ui/qwen-code/packages/core/src/test-utils/mockWorkspaceContext.ts ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi } from 'vitest';
8
+ import { WorkspaceContext } from '../utils/workspaceContext.js';
9
+
10
+ /**
11
+ * Creates a mock WorkspaceContext for testing
12
+ * @param rootDir The root directory to use for the mock
13
+ * @param additionalDirs Optional additional directories to include in the workspace
14
+ * @returns A mock WorkspaceContext instance
15
+ */
16
+ export function createMockWorkspaceContext(
17
+ rootDir: string,
18
+ additionalDirs: string[] = [],
19
+ ): WorkspaceContext {
20
+ const allDirs = [rootDir, ...additionalDirs];
21
+
22
+ const mockWorkspaceContext = {
23
+ addDirectory: vi.fn(),
24
+ getDirectories: vi.fn().mockReturnValue(allDirs),
25
+ isPathWithinWorkspace: vi
26
+ .fn()
27
+ .mockImplementation((path: string) =>
28
+ allDirs.some((dir) => path.startsWith(dir)),
29
+ ),
30
+ } as unknown as WorkspaceContext;
31
+
32
+ return mockWorkspaceContext;
33
+ }
projects/ui/qwen-code/packages/core/src/test-utils/tools.ts ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi } from 'vitest';
8
+ import {
9
+ BaseDeclarativeTool,
10
+ BaseToolInvocation,
11
+ ToolCallConfirmationDetails,
12
+ ToolInvocation,
13
+ ToolResult,
14
+ Kind,
15
+ } from '../tools/tools.js';
16
+ import {
17
+ ModifiableDeclarativeTool,
18
+ ModifyContext,
19
+ } from '../tools/modifiable-tool.js';
20
+
21
+ class MockToolInvocation extends BaseToolInvocation<
22
+ { [key: string]: unknown },
23
+ ToolResult
24
+ > {
25
+ constructor(
26
+ private readonly tool: MockTool,
27
+ params: { [key: string]: unknown },
28
+ ) {
29
+ super(params);
30
+ }
31
+
32
+ async execute(_abortSignal: AbortSignal): Promise<ToolResult> {
33
+ const result = this.tool.executeFn(this.params);
34
+ return (
35
+ result ?? {
36
+ llmContent: `Tool ${this.tool.name} executed successfully.`,
37
+ returnDisplay: `Tool ${this.tool.name} executed successfully.`,
38
+ }
39
+ );
40
+ }
41
+
42
+ override async shouldConfirmExecute(
43
+ _abortSignal: AbortSignal,
44
+ ): Promise<ToolCallConfirmationDetails | false> {
45
+ if (this.tool.shouldConfirm) {
46
+ return {
47
+ type: 'exec' as const,
48
+ title: `Confirm ${this.tool.displayName}`,
49
+ command: this.tool.name,
50
+ rootCommand: this.tool.name,
51
+ onConfirm: async () => {},
52
+ };
53
+ }
54
+ return false;
55
+ }
56
+
57
+ getDescription(): string {
58
+ return `A mock tool invocation for ${this.tool.name}`;
59
+ }
60
+ }
61
+
62
+ /**
63
+ * A highly configurable mock tool for testing purposes.
64
+ */
65
+ export class MockTool extends BaseDeclarativeTool<
66
+ { [key: string]: unknown },
67
+ ToolResult
68
+ > {
69
+ executeFn = vi.fn();
70
+ shouldConfirm = false;
71
+
72
+ constructor(
73
+ name = 'mock-tool',
74
+ displayName?: string,
75
+ description = 'A mock tool for testing.',
76
+ params = {
77
+ type: 'object',
78
+ properties: { param: { type: 'string' } },
79
+ },
80
+ ) {
81
+ super(name, displayName ?? name, description, Kind.Other, params);
82
+ }
83
+
84
+ protected createInvocation(params: {
85
+ [key: string]: unknown;
86
+ }): ToolInvocation<{ [key: string]: unknown }, ToolResult> {
87
+ return new MockToolInvocation(this, params);
88
+ }
89
+ }
90
+
91
+ export class MockModifiableToolInvocation extends BaseToolInvocation<
92
+ Record<string, unknown>,
93
+ ToolResult
94
+ > {
95
+ constructor(
96
+ private readonly tool: MockModifiableTool,
97
+ params: Record<string, unknown>,
98
+ ) {
99
+ super(params);
100
+ }
101
+
102
+ async execute(_abortSignal: AbortSignal): Promise<ToolResult> {
103
+ const result = this.tool.executeFn(this.params);
104
+ return (
105
+ result ?? {
106
+ llmContent: `Tool ${this.tool.name} executed successfully.`,
107
+ returnDisplay: `Tool ${this.tool.name} executed successfully.`,
108
+ }
109
+ );
110
+ }
111
+
112
+ override async shouldConfirmExecute(
113
+ _abortSignal: AbortSignal,
114
+ ): Promise<ToolCallConfirmationDetails | false> {
115
+ if (this.tool.shouldConfirm) {
116
+ return {
117
+ type: 'edit',
118
+ title: 'Confirm Mock Tool',
119
+ fileName: 'test.txt',
120
+ filePath: 'test.txt',
121
+ fileDiff: 'diff',
122
+ originalContent: 'originalContent',
123
+ newContent: 'newContent',
124
+ onConfirm: async () => {},
125
+ };
126
+ }
127
+ return false;
128
+ }
129
+
130
+ getDescription(): string {
131
+ return `A mock modifiable tool invocation for ${this.tool.name}`;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * Configurable mock modifiable tool for testing.
137
+ */
138
+ export class MockModifiableTool
139
+ extends MockTool
140
+ implements ModifiableDeclarativeTool<Record<string, unknown>>
141
+ {
142
+ constructor(name = 'mockModifiableTool') {
143
+ super(name);
144
+ this.shouldConfirm = true;
145
+ }
146
+
147
+ getModifyContext(
148
+ _abortSignal: AbortSignal,
149
+ ): ModifyContext<Record<string, unknown>> {
150
+ return {
151
+ getFilePath: () => 'test.txt',
152
+ getCurrentContent: async () => 'old content',
153
+ getProposedContent: async () => 'new content',
154
+ createUpdatedParams: (
155
+ _oldContent: string,
156
+ modifiedProposedContent: string,
157
+ _originalParams: Record<string, unknown>,
158
+ ) => ({ newContent: modifiedProposedContent }),
159
+ };
160
+ }
161
+
162
+ protected override createInvocation(
163
+ params: Record<string, unknown>,
164
+ ): ToolInvocation<Record<string, unknown>, ToolResult> {
165
+ return new MockModifiableToolInvocation(this, params);
166
+ }
167
+ }
projects/ui/qwen-code/packages/core/src/tools/diffOptions.test.ts ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, expect, it } from 'vitest';
8
+ import { getDiffStat } from './diffOptions.js';
9
+
10
+ describe('getDiffStat', () => {
11
+ const fileName = 'test.txt';
12
+
13
+ it('should return 0 for all stats when there are no changes', () => {
14
+ const oldStr = 'line1\nline2\n';
15
+ const aiStr = 'line1\nline2\n';
16
+ const userStr = 'line1\nline2\n';
17
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
18
+ expect(diffStat).toEqual({
19
+ ai_added_lines: 0,
20
+ ai_removed_lines: 0,
21
+ user_added_lines: 0,
22
+ user_removed_lines: 0,
23
+ });
24
+ });
25
+
26
+ it('should correctly report AI additions', () => {
27
+ const oldStr = 'line1\nline2\n';
28
+ const aiStr = 'line1\nline2\nline3\n';
29
+ const userStr = 'line1\nline2\nline3\n';
30
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
31
+ expect(diffStat).toEqual({
32
+ ai_added_lines: 1,
33
+ ai_removed_lines: 0,
34
+ user_added_lines: 0,
35
+ user_removed_lines: 0,
36
+ });
37
+ });
38
+
39
+ it('should correctly report AI removals', () => {
40
+ const oldStr = 'line1\nline2\nline3\n';
41
+ const aiStr = 'line1\nline3\n';
42
+ const userStr = 'line1\nline3\n';
43
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
44
+ expect(diffStat).toEqual({
45
+ ai_added_lines: 0,
46
+ ai_removed_lines: 1,
47
+ user_added_lines: 0,
48
+ user_removed_lines: 0,
49
+ });
50
+ });
51
+
52
+ it('should correctly report AI modifications', () => {
53
+ const oldStr = 'line1\nline2\nline3\n';
54
+ const aiStr = 'line1\nline_two\nline3\n';
55
+ const userStr = 'line1\nline_two\nline3\n';
56
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
57
+ expect(diffStat).toEqual({
58
+ ai_added_lines: 1,
59
+ ai_removed_lines: 1,
60
+ user_added_lines: 0,
61
+ user_removed_lines: 0,
62
+ });
63
+ });
64
+
65
+ it('should correctly report user additions', () => {
66
+ const oldStr = 'line1\nline2\n';
67
+ const aiStr = 'line1\nline2\nline3\n';
68
+ const userStr = 'line1\nline2\nline3\nline4\n';
69
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
70
+ expect(diffStat).toEqual({
71
+ ai_added_lines: 1,
72
+ ai_removed_lines: 0,
73
+ user_added_lines: 1,
74
+ user_removed_lines: 0,
75
+ });
76
+ });
77
+
78
+ it('should correctly report user removals', () => {
79
+ const oldStr = 'line1\nline2\n';
80
+ const aiStr = 'line1\nline2\nline3\n';
81
+ const userStr = 'line1\nline2\n';
82
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
83
+ expect(diffStat).toEqual({
84
+ ai_added_lines: 1,
85
+ ai_removed_lines: 0,
86
+ user_added_lines: 0,
87
+ user_removed_lines: 1,
88
+ });
89
+ });
90
+
91
+ it('should correctly report user modifications', () => {
92
+ const oldStr = 'line1\nline2\n';
93
+ const aiStr = 'line1\nline2\nline3\n';
94
+ const userStr = 'line1\nline2\nline_three\n';
95
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
96
+ expect(diffStat).toEqual({
97
+ ai_added_lines: 1,
98
+ ai_removed_lines: 0,
99
+ user_added_lines: 1,
100
+ user_removed_lines: 1,
101
+ });
102
+ });
103
+
104
+ it('should handle complex changes from both AI and user', () => {
105
+ const oldStr = 'line1\nline2\nline3\nline4\n';
106
+ const aiStr = 'line_one\nline2\nline_three\nline4\n';
107
+ const userStr = 'line_one\nline_two\nline_three\nline4\nline5\n';
108
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
109
+ expect(diffStat).toEqual({
110
+ ai_added_lines: 2,
111
+ ai_removed_lines: 2,
112
+ user_added_lines: 2,
113
+ user_removed_lines: 1,
114
+ });
115
+ });
116
+
117
+ it('should report a single line modification as one addition and one removal', () => {
118
+ const oldStr = 'hello world';
119
+ const aiStr = 'hello universe';
120
+ const userStr = 'hello universe';
121
+ const diffStat = getDiffStat(fileName, oldStr, aiStr, userStr);
122
+ expect(diffStat).toEqual({
123
+ ai_added_lines: 1,
124
+ ai_removed_lines: 1,
125
+ user_added_lines: 0,
126
+ user_removed_lines: 0,
127
+ });
128
+ });
129
+ });
projects/ui/qwen-code/packages/core/src/tools/diffOptions.ts ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as Diff from 'diff';
8
+ import { DiffStat } from './tools.js';
9
+
10
+ export const DEFAULT_DIFF_OPTIONS: Diff.PatchOptions = {
11
+ context: 3,
12
+ ignoreWhitespace: true,
13
+ };
14
+
15
+ export function getDiffStat(
16
+ fileName: string,
17
+ oldStr: string,
18
+ aiStr: string,
19
+ userStr: string,
20
+ ): DiffStat {
21
+ const countLines = (patch: Diff.ParsedDiff) => {
22
+ let added = 0;
23
+ let removed = 0;
24
+ patch.hunks.forEach((hunk: Diff.Hunk) => {
25
+ hunk.lines.forEach((line: string) => {
26
+ if (line.startsWith('+')) {
27
+ added++;
28
+ } else if (line.startsWith('-')) {
29
+ removed++;
30
+ }
31
+ });
32
+ });
33
+ return { added, removed };
34
+ };
35
+
36
+ const patch = Diff.structuredPatch(
37
+ fileName,
38
+ fileName,
39
+ oldStr,
40
+ aiStr,
41
+ 'Current',
42
+ 'Proposed',
43
+ DEFAULT_DIFF_OPTIONS,
44
+ );
45
+ const { added: aiAddedLines, removed: aiRemovedLines } = countLines(patch);
46
+
47
+ const userPatch = Diff.structuredPatch(
48
+ fileName,
49
+ fileName,
50
+ aiStr,
51
+ userStr,
52
+ 'Proposed',
53
+ 'User',
54
+ DEFAULT_DIFF_OPTIONS,
55
+ );
56
+ const { added: userAddedLines, removed: userRemovedLines } =
57
+ countLines(userPatch);
58
+
59
+ return {
60
+ ai_added_lines: aiAddedLines,
61
+ ai_removed_lines: aiRemovedLines,
62
+ user_added_lines: userAddedLines,
63
+ user_removed_lines: userRemovedLines,
64
+ };
65
+ }
projects/ui/qwen-code/packages/core/src/tools/edit.test.ts ADDED
@@ -0,0 +1,862 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /* eslint-disable @typescript-eslint/no-explicit-any */
8
+
9
+ const mockEnsureCorrectEdit = vi.hoisted(() => vi.fn());
10
+ const mockGenerateJson = vi.hoisted(() => vi.fn());
11
+ const mockOpenDiff = vi.hoisted(() => vi.fn());
12
+
13
+ import { IDEConnectionStatus } from '../ide/ide-client.js';
14
+
15
+ vi.mock('../utils/editCorrector.js', () => ({
16
+ ensureCorrectEdit: mockEnsureCorrectEdit,
17
+ }));
18
+
19
+ vi.mock('../core/client.js', () => ({
20
+ GeminiClient: vi.fn().mockImplementation(() => ({
21
+ generateJson: mockGenerateJson,
22
+ })),
23
+ }));
24
+
25
+ vi.mock('../utils/editor.js', () => ({
26
+ openDiff: mockOpenDiff,
27
+ }));
28
+
29
+ import { describe, it, expect, beforeEach, afterEach, vi, Mock } from 'vitest';
30
+ import { applyReplacement, EditTool, EditToolParams } from './edit.js';
31
+ import { FileDiff, ToolConfirmationOutcome } from './tools.js';
32
+ import { ToolErrorType } from './tool-error.js';
33
+ import path from 'path';
34
+ import fs from 'fs';
35
+ import os from 'os';
36
+ import { ApprovalMode, Config } from '../config/config.js';
37
+ import { Content, Part, SchemaUnion } from '@google/genai';
38
+ import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js';
39
+ import { StandardFileSystemService } from '../services/fileSystemService.js';
40
+
41
+ describe('EditTool', () => {
42
+ let tool: EditTool;
43
+ let tempDir: string;
44
+ let rootDir: string;
45
+ let mockConfig: Config;
46
+ let geminiClient: any;
47
+
48
+ beforeEach(() => {
49
+ vi.restoreAllMocks();
50
+ tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'edit-tool-test-'));
51
+ rootDir = path.join(tempDir, 'root');
52
+ fs.mkdirSync(rootDir);
53
+
54
+ geminiClient = {
55
+ generateJson: mockGenerateJson, // mockGenerateJson is already defined and hoisted
56
+ };
57
+
58
+ mockConfig = {
59
+ getGeminiClient: vi.fn().mockReturnValue(geminiClient),
60
+ getTargetDir: () => rootDir,
61
+ getApprovalMode: vi.fn(),
62
+ setApprovalMode: vi.fn(),
63
+ getWorkspaceContext: () => createMockWorkspaceContext(rootDir),
64
+ getFileSystemService: () => new StandardFileSystemService(),
65
+ getIdeClient: () => undefined,
66
+ getIdeMode: () => false,
67
+ // getGeminiConfig: () => ({ apiKey: 'test-api-key' }), // This was not a real Config method
68
+ // Add other properties/methods of Config if EditTool uses them
69
+ // Minimal other methods to satisfy Config type if needed by EditTool constructor or other direct uses:
70
+ getApiKey: () => 'test-api-key',
71
+ getModel: () => 'test-model',
72
+ getSandbox: () => false,
73
+ getDebugMode: () => false,
74
+ getQuestion: () => undefined,
75
+ getFullContext: () => false,
76
+ getToolDiscoveryCommand: () => undefined,
77
+ getToolCallCommand: () => undefined,
78
+ getMcpServerCommand: () => undefined,
79
+ getMcpServers: () => undefined,
80
+ getUserAgent: () => 'test-agent',
81
+ getUserMemory: () => '',
82
+ setUserMemory: vi.fn(),
83
+ getGeminiMdFileCount: () => 0,
84
+ setGeminiMdFileCount: vi.fn(),
85
+ getToolRegistry: () => ({}) as any, // Minimal mock for ToolRegistry
86
+ } as unknown as Config;
87
+
88
+ // Reset mocks before each test
89
+ (mockConfig.getApprovalMode as Mock).mockClear();
90
+ // Default to not skipping confirmation
91
+ (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.DEFAULT);
92
+
93
+ // Reset mocks and set default implementation for ensureCorrectEdit
94
+ mockEnsureCorrectEdit.mockReset();
95
+ mockEnsureCorrectEdit.mockImplementation(
96
+ async (_, currentContent, params) => {
97
+ let occurrences = 0;
98
+ if (params.old_string && currentContent) {
99
+ // Simple string counting for the mock
100
+ let index = currentContent.indexOf(params.old_string);
101
+ while (index !== -1) {
102
+ occurrences++;
103
+ index = currentContent.indexOf(params.old_string, index + 1);
104
+ }
105
+ } else if (params.old_string === '') {
106
+ occurrences = 0; // Creating a new file
107
+ }
108
+ return Promise.resolve({ params, occurrences });
109
+ },
110
+ );
111
+
112
+ // Default mock for generateJson to return the snippet unchanged
113
+ mockGenerateJson.mockReset();
114
+ mockGenerateJson.mockImplementation(
115
+ async (contents: Content[], schema: SchemaUnion) => {
116
+ // The problematic_snippet is the last part of the user's content
117
+ const userContent = contents.find((c: Content) => c.role === 'user');
118
+ let promptText = '';
119
+ if (userContent && userContent.parts) {
120
+ promptText = userContent.parts
121
+ .filter((p: Part) => typeof (p as any).text === 'string')
122
+ .map((p: Part) => (p as any).text)
123
+ .join('\n');
124
+ }
125
+ const snippetMatch = promptText.match(
126
+ /Problematic target snippet:\n```\n([\s\S]*?)\n```/,
127
+ );
128
+ const problematicSnippet =
129
+ snippetMatch && snippetMatch[1] ? snippetMatch[1] : '';
130
+
131
+ if (((schema as any).properties as any)?.corrected_target_snippet) {
132
+ return Promise.resolve({
133
+ corrected_target_snippet: problematicSnippet,
134
+ });
135
+ }
136
+ if (((schema as any).properties as any)?.corrected_new_string) {
137
+ // For new_string correction, we might need more sophisticated logic,
138
+ // but for now, returning original is a safe default if not specified by a test.
139
+ const originalNewStringMatch = promptText.match(
140
+ /original_new_string \(what was intended to replace original_old_string\):\n```\n([\s\S]*?)\n```/,
141
+ );
142
+ const originalNewString =
143
+ originalNewStringMatch && originalNewStringMatch[1]
144
+ ? originalNewStringMatch[1]
145
+ : '';
146
+ return Promise.resolve({ corrected_new_string: originalNewString });
147
+ }
148
+ return Promise.resolve({}); // Default empty object if schema doesn't match
149
+ },
150
+ );
151
+
152
+ tool = new EditTool(mockConfig);
153
+ });
154
+
155
+ afterEach(() => {
156
+ fs.rmSync(tempDir, { recursive: true, force: true });
157
+ });
158
+
159
+ describe('applyReplacement', () => {
160
+ it('should return newString if isNewFile is true', () => {
161
+ expect(applyReplacement(null, 'old', 'new', true)).toBe('new');
162
+ expect(applyReplacement('existing', 'old', 'new', true)).toBe('new');
163
+ });
164
+
165
+ it('should return newString if currentContent is null and oldString is empty (defensive)', () => {
166
+ expect(applyReplacement(null, '', 'new', false)).toBe('new');
167
+ });
168
+
169
+ it('should return empty string if currentContent is null and oldString is not empty (defensive)', () => {
170
+ expect(applyReplacement(null, 'old', 'new', false)).toBe('');
171
+ });
172
+
173
+ it('should replace oldString with newString in currentContent', () => {
174
+ expect(applyReplacement('hello old world old', 'old', 'new', false)).toBe(
175
+ 'hello new world new',
176
+ );
177
+ });
178
+
179
+ it('should return currentContent if oldString is empty and not a new file', () => {
180
+ expect(applyReplacement('hello world', '', 'new', false)).toBe(
181
+ 'hello world',
182
+ );
183
+ });
184
+ });
185
+
186
+ describe('validateToolParams', () => {
187
+ it('should return null for valid params', () => {
188
+ const params: EditToolParams = {
189
+ file_path: path.join(rootDir, 'test.txt'),
190
+ old_string: 'old',
191
+ new_string: 'new',
192
+ };
193
+ expect(tool.validateToolParams(params)).toBeNull();
194
+ });
195
+
196
+ it('should return error for relative path', () => {
197
+ const params: EditToolParams = {
198
+ file_path: 'test.txt',
199
+ old_string: 'old',
200
+ new_string: 'new',
201
+ };
202
+ expect(tool.validateToolParams(params)).toMatch(
203
+ /File path must be absolute/,
204
+ );
205
+ });
206
+
207
+ it('should return error for path outside root', () => {
208
+ const params: EditToolParams = {
209
+ file_path: path.join(tempDir, 'outside-root.txt'),
210
+ old_string: 'old',
211
+ new_string: 'new',
212
+ };
213
+ const error = tool.validateToolParams(params);
214
+ expect(error).toContain(
215
+ 'File path must be within one of the workspace directories',
216
+ );
217
+ });
218
+ });
219
+
220
+ describe('shouldConfirmExecute', () => {
221
+ const testFile = 'edit_me.txt';
222
+ let filePath: string;
223
+
224
+ beforeEach(() => {
225
+ filePath = path.join(rootDir, testFile);
226
+ });
227
+
228
+ it('should throw an error if params are invalid', async () => {
229
+ const params: EditToolParams = {
230
+ file_path: 'relative.txt',
231
+ old_string: 'old',
232
+ new_string: 'new',
233
+ };
234
+ expect(() => tool.build(params)).toThrow();
235
+ });
236
+
237
+ it('should request confirmation for valid edit', async () => {
238
+ fs.writeFileSync(filePath, 'some old content here');
239
+ const params: EditToolParams = {
240
+ file_path: filePath,
241
+ old_string: 'old',
242
+ new_string: 'new',
243
+ };
244
+ // ensureCorrectEdit will be called by shouldConfirmExecute
245
+ mockEnsureCorrectEdit.mockResolvedValueOnce({ params, occurrences: 1 });
246
+ const invocation = tool.build(params);
247
+ const confirmation = await invocation.shouldConfirmExecute(
248
+ new AbortController().signal,
249
+ );
250
+ expect(confirmation).toEqual(
251
+ expect.objectContaining({
252
+ title: `Confirm Edit: ${testFile}`,
253
+ fileName: testFile,
254
+ fileDiff: expect.any(String),
255
+ }),
256
+ );
257
+ });
258
+
259
+ it('should return false if old_string is not found (ensureCorrectEdit returns 0)', async () => {
260
+ fs.writeFileSync(filePath, 'some content here');
261
+ const params: EditToolParams = {
262
+ file_path: filePath,
263
+ old_string: 'not_found',
264
+ new_string: 'new',
265
+ };
266
+ mockEnsureCorrectEdit.mockResolvedValueOnce({ params, occurrences: 0 });
267
+ const invocation = tool.build(params);
268
+ const confirmation = await invocation.shouldConfirmExecute(
269
+ new AbortController().signal,
270
+ );
271
+ expect(confirmation).toBe(false);
272
+ });
273
+
274
+ it('should return false if multiple occurrences of old_string are found (ensureCorrectEdit returns > 1)', async () => {
275
+ fs.writeFileSync(filePath, 'old old content here');
276
+ const params: EditToolParams = {
277
+ file_path: filePath,
278
+ old_string: 'old',
279
+ new_string: 'new',
280
+ };
281
+ mockEnsureCorrectEdit.mockResolvedValueOnce({ params, occurrences: 2 });
282
+ const invocation = tool.build(params);
283
+ const confirmation = await invocation.shouldConfirmExecute(
284
+ new AbortController().signal,
285
+ );
286
+ expect(confirmation).toBe(false);
287
+ });
288
+
289
+ it('should request confirmation for creating a new file (empty old_string)', async () => {
290
+ const newFileName = 'new_file.txt';
291
+ const newFilePath = path.join(rootDir, newFileName);
292
+ const params: EditToolParams = {
293
+ file_path: newFilePath,
294
+ old_string: '',
295
+ new_string: 'new file content',
296
+ };
297
+ // ensureCorrectEdit might not be called if old_string is empty,
298
+ // as shouldConfirmExecute handles this for diff generation.
299
+ // If it is called, it should return 0 occurrences for a new file.
300
+ mockEnsureCorrectEdit.mockResolvedValueOnce({ params, occurrences: 0 });
301
+ const invocation = tool.build(params);
302
+ const confirmation = await invocation.shouldConfirmExecute(
303
+ new AbortController().signal,
304
+ );
305
+ expect(confirmation).toEqual(
306
+ expect.objectContaining({
307
+ title: `Confirm Edit: ${newFileName}`,
308
+ fileName: newFileName,
309
+ fileDiff: expect.any(String),
310
+ }),
311
+ );
312
+ });
313
+
314
+ it('should use corrected params from ensureCorrectEdit for diff generation', async () => {
315
+ const originalContent = 'This is the original string to be replaced.';
316
+ const originalOldString = 'original string';
317
+ const originalNewString = 'new string';
318
+
319
+ const correctedOldString = 'original string to be replaced'; // More specific
320
+ const correctedNewString = 'completely new string'; // Different replacement
321
+ const expectedFinalContent = 'This is the completely new string.';
322
+
323
+ fs.writeFileSync(filePath, originalContent);
324
+ const params: EditToolParams = {
325
+ file_path: filePath,
326
+ old_string: originalOldString,
327
+ new_string: originalNewString,
328
+ };
329
+
330
+ // The main beforeEach already calls mockEnsureCorrectEdit.mockReset()
331
+ // Set a specific mock for this test case
332
+ let mockCalled = false;
333
+ mockEnsureCorrectEdit.mockImplementationOnce(
334
+ async (_, content, p, client) => {
335
+ mockCalled = true;
336
+ expect(content).toBe(originalContent);
337
+ expect(p).toBe(params);
338
+ expect(client).toBe(geminiClient);
339
+ return {
340
+ params: {
341
+ file_path: filePath,
342
+ old_string: correctedOldString,
343
+ new_string: correctedNewString,
344
+ },
345
+ occurrences: 1,
346
+ };
347
+ },
348
+ );
349
+ const invocation = tool.build(params);
350
+ const confirmation = (await invocation.shouldConfirmExecute(
351
+ new AbortController().signal,
352
+ )) as FileDiff;
353
+
354
+ expect(mockCalled).toBe(true); // Check if the mock implementation was run
355
+ // expect(mockEnsureCorrectEdit).toHaveBeenCalledWith(originalContent, params, expect.anything()); // Keep this commented for now
356
+ expect(confirmation).toEqual(
357
+ expect.objectContaining({
358
+ title: `Confirm Edit: ${testFile}`,
359
+ fileName: testFile,
360
+ }),
361
+ );
362
+ // Check that the diff is based on the corrected strings leading to the new state
363
+ expect(confirmation.fileDiff).toContain(`-${originalContent}`);
364
+ expect(confirmation.fileDiff).toContain(`+${expectedFinalContent}`);
365
+
366
+ // Verify that applying the correctedOldString and correctedNewString to originalContent
367
+ // indeed produces the expectedFinalContent, which is what the diff should reflect.
368
+ const patchedContent = originalContent.replace(
369
+ correctedOldString, // This was the string identified by ensureCorrectEdit for replacement
370
+ correctedNewString, // This was the string identified by ensureCorrectEdit as the replacement
371
+ );
372
+ expect(patchedContent).toBe(expectedFinalContent);
373
+ });
374
+ });
375
+
376
+ describe('execute', () => {
377
+ const testFile = 'execute_me.txt';
378
+ let filePath: string;
379
+
380
+ beforeEach(() => {
381
+ filePath = path.join(rootDir, testFile);
382
+ // Default for execute tests, can be overridden
383
+ mockEnsureCorrectEdit.mockImplementation(async (_, content, params) => {
384
+ let occurrences = 0;
385
+ if (params.old_string && content) {
386
+ let index = content.indexOf(params.old_string);
387
+ while (index !== -1) {
388
+ occurrences++;
389
+ index = content.indexOf(params.old_string, index + 1);
390
+ }
391
+ } else if (params.old_string === '') {
392
+ occurrences = 0;
393
+ }
394
+ return { params, occurrences };
395
+ });
396
+ });
397
+
398
+ it('should throw error if file path is not absolute', async () => {
399
+ const params: EditToolParams = {
400
+ file_path: 'relative.txt',
401
+ old_string: 'old',
402
+ new_string: 'new',
403
+ };
404
+ expect(() => tool.build(params)).toThrow(/File path must be absolute/);
405
+ });
406
+
407
+ it('should throw error if file path is empty', async () => {
408
+ const params: EditToolParams = {
409
+ file_path: '',
410
+ old_string: 'old',
411
+ new_string: 'new',
412
+ };
413
+ expect(() => tool.build(params)).toThrow(
414
+ /The 'file_path' parameter must be non-empty./,
415
+ );
416
+ });
417
+
418
+ it('should edit an existing file and return diff with fileName', async () => {
419
+ const initialContent = 'This is some old text.';
420
+ const newContent = 'This is some new text.'; // old -> new
421
+ fs.writeFileSync(filePath, initialContent, 'utf8');
422
+ const params: EditToolParams = {
423
+ file_path: filePath,
424
+ old_string: 'old',
425
+ new_string: 'new',
426
+ };
427
+
428
+ // Specific mock for this test's execution path in calculateEdit
429
+ // ensureCorrectEdit is NOT called by calculateEdit, only by shouldConfirmExecute
430
+ // So, the default mockEnsureCorrectEdit should correctly return 1 occurrence for 'old' in initialContent
431
+
432
+ const invocation = tool.build(params);
433
+ const result = await invocation.execute(new AbortController().signal);
434
+
435
+ expect(result.llmContent).toMatch(/Successfully modified file/);
436
+ expect(fs.readFileSync(filePath, 'utf8')).toBe(newContent);
437
+ const display = result.returnDisplay as FileDiff;
438
+ expect(display.fileDiff).toMatch(initialContent);
439
+ expect(display.fileDiff).toMatch(newContent);
440
+ expect(display.fileName).toBe(testFile);
441
+ });
442
+
443
+ it('should create a new file if old_string is empty and file does not exist, and return created message', async () => {
444
+ const newFileName = 'brand_new_file.txt';
445
+ const newFilePath = path.join(rootDir, newFileName);
446
+ const fileContent = 'Content for the new file.';
447
+ const params: EditToolParams = {
448
+ file_path: newFilePath,
449
+ old_string: '',
450
+ new_string: fileContent,
451
+ };
452
+
453
+ (mockConfig.getApprovalMode as Mock).mockReturnValueOnce(
454
+ ApprovalMode.AUTO_EDIT,
455
+ );
456
+ const invocation = tool.build(params);
457
+ const result = await invocation.execute(new AbortController().signal);
458
+
459
+ expect(result.llmContent).toMatch(/Created new file/);
460
+ expect(fs.existsSync(newFilePath)).toBe(true);
461
+ expect(fs.readFileSync(newFilePath, 'utf8')).toBe(fileContent);
462
+ expect(result.returnDisplay).toBe(`Created ${newFileName}`);
463
+ });
464
+
465
+ it('should return error if old_string is not found in file', async () => {
466
+ fs.writeFileSync(filePath, 'Some content.', 'utf8');
467
+ const params: EditToolParams = {
468
+ file_path: filePath,
469
+ old_string: 'nonexistent',
470
+ new_string: 'replacement',
471
+ };
472
+ // The default mockEnsureCorrectEdit will return 0 occurrences for 'nonexistent'
473
+ const invocation = tool.build(params);
474
+ const result = await invocation.execute(new AbortController().signal);
475
+ expect(result.llmContent).toMatch(
476
+ /0 occurrences found for old_string in/,
477
+ );
478
+ expect(result.returnDisplay).toMatch(
479
+ /Failed to edit, could not find the string to replace./,
480
+ );
481
+ });
482
+
483
+ it('should return error if multiple occurrences of old_string are found', async () => {
484
+ fs.writeFileSync(filePath, 'multiple old old strings', 'utf8');
485
+ const params: EditToolParams = {
486
+ file_path: filePath,
487
+ old_string: 'old',
488
+ new_string: 'new',
489
+ };
490
+ // The default mockEnsureCorrectEdit will return 2 occurrences for 'old'
491
+ const invocation = tool.build(params);
492
+ const result = await invocation.execute(new AbortController().signal);
493
+ expect(result.llmContent).toMatch(
494
+ /Expected 1 occurrence but found 2 for old_string in file/,
495
+ );
496
+ expect(result.returnDisplay).toMatch(
497
+ /Failed to edit, expected 1 occurrence but found 2/,
498
+ );
499
+ });
500
+
501
+ it('should successfully replace multiple occurrences when expected_replacements specified', async () => {
502
+ fs.writeFileSync(filePath, 'old text old text old text', 'utf8');
503
+ const params: EditToolParams = {
504
+ file_path: filePath,
505
+ old_string: 'old',
506
+ new_string: 'new',
507
+ expected_replacements: 3,
508
+ };
509
+
510
+ const invocation = tool.build(params);
511
+ const result = await invocation.execute(new AbortController().signal);
512
+
513
+ expect(result.llmContent).toMatch(/Successfully modified file/);
514
+ expect(fs.readFileSync(filePath, 'utf8')).toBe(
515
+ 'new text new text new text',
516
+ );
517
+ const display = result.returnDisplay as FileDiff;
518
+ expect(display.fileDiff).toMatch(/old text old text old text/);
519
+ expect(display.fileDiff).toMatch(/new text new text new text/);
520
+ expect(display.fileName).toBe(testFile);
521
+ });
522
+
523
+ it('should return error if expected_replacements does not match actual occurrences', async () => {
524
+ fs.writeFileSync(filePath, 'old text old text', 'utf8');
525
+ const params: EditToolParams = {
526
+ file_path: filePath,
527
+ old_string: 'old',
528
+ new_string: 'new',
529
+ expected_replacements: 3, // Expecting 3 but only 2 exist
530
+ };
531
+ const invocation = tool.build(params);
532
+ const result = await invocation.execute(new AbortController().signal);
533
+ expect(result.llmContent).toMatch(
534
+ /Expected 3 occurrences but found 2 for old_string in file/,
535
+ );
536
+ expect(result.returnDisplay).toMatch(
537
+ /Failed to edit, expected 3 occurrences but found 2/,
538
+ );
539
+ });
540
+
541
+ it('should return error if trying to create a file that already exists (empty old_string)', async () => {
542
+ fs.writeFileSync(filePath, 'Existing content', 'utf8');
543
+ const params: EditToolParams = {
544
+ file_path: filePath,
545
+ old_string: '',
546
+ new_string: 'new content',
547
+ };
548
+ const invocation = tool.build(params);
549
+ const result = await invocation.execute(new AbortController().signal);
550
+ expect(result.llmContent).toMatch(/File already exists, cannot create/);
551
+ expect(result.returnDisplay).toMatch(
552
+ /Attempted to create a file that already exists/,
553
+ );
554
+ });
555
+
556
+ it('should include modification message when proposed content is modified', async () => {
557
+ const initialContent = 'This is some old text.';
558
+ fs.writeFileSync(filePath, initialContent, 'utf8');
559
+ const params: EditToolParams = {
560
+ file_path: filePath,
561
+ old_string: 'old',
562
+ new_string: 'new',
563
+ modified_by_user: true,
564
+ };
565
+
566
+ (mockConfig.getApprovalMode as Mock).mockReturnValueOnce(
567
+ ApprovalMode.AUTO_EDIT,
568
+ );
569
+ const invocation = tool.build(params);
570
+ const result = await invocation.execute(new AbortController().signal);
571
+
572
+ expect(result.llmContent).toMatch(
573
+ /User modified the `new_string` content/,
574
+ );
575
+ });
576
+
577
+ it('should not include modification message when proposed content is not modified', async () => {
578
+ const initialContent = 'This is some old text.';
579
+ fs.writeFileSync(filePath, initialContent, 'utf8');
580
+ const params: EditToolParams = {
581
+ file_path: filePath,
582
+ old_string: 'old',
583
+ new_string: 'new',
584
+ modified_by_user: false,
585
+ };
586
+
587
+ (mockConfig.getApprovalMode as Mock).mockReturnValueOnce(
588
+ ApprovalMode.AUTO_EDIT,
589
+ );
590
+ const invocation = tool.build(params);
591
+ const result = await invocation.execute(new AbortController().signal);
592
+
593
+ expect(result.llmContent).not.toMatch(
594
+ /User modified the `new_string` content/,
595
+ );
596
+ });
597
+
598
+ it('should not include modification message when modified_by_user is not provided', async () => {
599
+ const initialContent = 'This is some old text.';
600
+ fs.writeFileSync(filePath, initialContent, 'utf8');
601
+ const params: EditToolParams = {
602
+ file_path: filePath,
603
+ old_string: 'old',
604
+ new_string: 'new',
605
+ };
606
+
607
+ (mockConfig.getApprovalMode as Mock).mockReturnValueOnce(
608
+ ApprovalMode.AUTO_EDIT,
609
+ );
610
+ const invocation = tool.build(params);
611
+ const result = await invocation.execute(new AbortController().signal);
612
+
613
+ expect(result.llmContent).not.toMatch(
614
+ /User modified the `new_string` content/,
615
+ );
616
+ });
617
+
618
+ it('should return error if old_string and new_string are identical', async () => {
619
+ const initialContent = 'This is some identical text.';
620
+ fs.writeFileSync(filePath, initialContent, 'utf8');
621
+ const params: EditToolParams = {
622
+ file_path: filePath,
623
+ old_string: 'identical',
624
+ new_string: 'identical',
625
+ };
626
+ const invocation = tool.build(params);
627
+ const result = await invocation.execute(new AbortController().signal);
628
+ expect(result.llmContent).toMatch(/No changes to apply/);
629
+ expect(result.returnDisplay).toMatch(/No changes to apply/);
630
+ });
631
+ });
632
+
633
+ describe('Error Scenarios', () => {
634
+ const testFile = 'error_test.txt';
635
+ let filePath: string;
636
+
637
+ beforeEach(() => {
638
+ filePath = path.join(rootDir, testFile);
639
+ });
640
+
641
+ it('should return FILE_NOT_FOUND error', async () => {
642
+ const params: EditToolParams = {
643
+ file_path: filePath,
644
+ old_string: 'any',
645
+ new_string: 'new',
646
+ };
647
+ const invocation = tool.build(params);
648
+ const result = await invocation.execute(new AbortController().signal);
649
+ expect(result.error?.type).toBe(ToolErrorType.FILE_NOT_FOUND);
650
+ });
651
+
652
+ it('should return ATTEMPT_TO_CREATE_EXISTING_FILE error', async () => {
653
+ fs.writeFileSync(filePath, 'existing content', 'utf8');
654
+ const params: EditToolParams = {
655
+ file_path: filePath,
656
+ old_string: '',
657
+ new_string: 'new content',
658
+ };
659
+ const invocation = tool.build(params);
660
+ const result = await invocation.execute(new AbortController().signal);
661
+ expect(result.error?.type).toBe(
662
+ ToolErrorType.ATTEMPT_TO_CREATE_EXISTING_FILE,
663
+ );
664
+ });
665
+
666
+ it('should return NO_OCCURRENCE_FOUND error', async () => {
667
+ fs.writeFileSync(filePath, 'content', 'utf8');
668
+ const params: EditToolParams = {
669
+ file_path: filePath,
670
+ old_string: 'not-found',
671
+ new_string: 'new',
672
+ };
673
+ const invocation = tool.build(params);
674
+ const result = await invocation.execute(new AbortController().signal);
675
+ expect(result.error?.type).toBe(ToolErrorType.EDIT_NO_OCCURRENCE_FOUND);
676
+ });
677
+
678
+ it('should return EXPECTED_OCCURRENCE_MISMATCH error', async () => {
679
+ fs.writeFileSync(filePath, 'one one two', 'utf8');
680
+ const params: EditToolParams = {
681
+ file_path: filePath,
682
+ old_string: 'one',
683
+ new_string: 'new',
684
+ expected_replacements: 3,
685
+ };
686
+ const invocation = tool.build(params);
687
+ const result = await invocation.execute(new AbortController().signal);
688
+ expect(result.error?.type).toBe(
689
+ ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
690
+ );
691
+ });
692
+
693
+ it('should return NO_CHANGE error', async () => {
694
+ fs.writeFileSync(filePath, 'content', 'utf8');
695
+ const params: EditToolParams = {
696
+ file_path: filePath,
697
+ old_string: 'content',
698
+ new_string: 'content',
699
+ };
700
+ const invocation = tool.build(params);
701
+ const result = await invocation.execute(new AbortController().signal);
702
+ expect(result.error?.type).toBe(ToolErrorType.EDIT_NO_CHANGE);
703
+ });
704
+
705
+ it('should throw INVALID_PARAMETERS error for relative path', async () => {
706
+ const params: EditToolParams = {
707
+ file_path: 'relative/path.txt',
708
+ old_string: 'a',
709
+ new_string: 'b',
710
+ };
711
+ expect(() => tool.build(params)).toThrow();
712
+ });
713
+
714
+ it('should return FILE_WRITE_FAILURE on write error', async () => {
715
+ fs.writeFileSync(filePath, 'content', 'utf8');
716
+ // Make file readonly to trigger a write error
717
+ fs.chmodSync(filePath, '444');
718
+
719
+ const params: EditToolParams = {
720
+ file_path: filePath,
721
+ old_string: 'content',
722
+ new_string: 'new content',
723
+ };
724
+ const invocation = tool.build(params);
725
+ const result = await invocation.execute(new AbortController().signal);
726
+ expect(result.error?.type).toBe(ToolErrorType.FILE_WRITE_FAILURE);
727
+ });
728
+ });
729
+
730
+ describe('getDescription', () => {
731
+ it('should return "No file changes to..." if old_string and new_string are the same', () => {
732
+ const testFileName = 'test.txt';
733
+ const params: EditToolParams = {
734
+ file_path: path.join(rootDir, testFileName),
735
+ old_string: 'identical_string',
736
+ new_string: 'identical_string',
737
+ };
738
+ const invocation = tool.build(params);
739
+ // shortenPath will be called internally, resulting in just the file name
740
+ expect(invocation.getDescription()).toBe(
741
+ `No file changes to ${testFileName}`,
742
+ );
743
+ });
744
+
745
+ it('should return a snippet of old and new strings if they are different', () => {
746
+ const testFileName = 'test.txt';
747
+ const params: EditToolParams = {
748
+ file_path: path.join(rootDir, testFileName),
749
+ old_string: 'this is the old string value',
750
+ new_string: 'this is the new string value',
751
+ };
752
+ const invocation = tool.build(params);
753
+ // shortenPath will be called internally, resulting in just the file name
754
+ // The snippets are truncated at 30 chars + '...'
755
+ expect(invocation.getDescription()).toBe(
756
+ `${testFileName}: this is the old string value => this is the new string value`,
757
+ );
758
+ });
759
+
760
+ it('should handle very short strings correctly in the description', () => {
761
+ const testFileName = 'short.txt';
762
+ const params: EditToolParams = {
763
+ file_path: path.join(rootDir, testFileName),
764
+ old_string: 'old',
765
+ new_string: 'new',
766
+ };
767
+ const invocation = tool.build(params);
768
+ expect(invocation.getDescription()).toBe(`${testFileName}: old => new`);
769
+ });
770
+
771
+ it('should truncate long strings in the description', () => {
772
+ const testFileName = 'long.txt';
773
+ const params: EditToolParams = {
774
+ file_path: path.join(rootDir, testFileName),
775
+ old_string:
776
+ 'this is a very long old string that will definitely be truncated',
777
+ new_string:
778
+ 'this is a very long new string that will also be truncated',
779
+ };
780
+ const invocation = tool.build(params);
781
+ expect(invocation.getDescription()).toBe(
782
+ `${testFileName}: this is a very long old string... => this is a very long new string...`,
783
+ );
784
+ });
785
+ });
786
+
787
+ describe('workspace boundary validation', () => {
788
+ it('should validate paths are within workspace root', () => {
789
+ const validPath = {
790
+ file_path: path.join(rootDir, 'file.txt'),
791
+ old_string: 'old',
792
+ new_string: 'new',
793
+ };
794
+ expect(tool.validateToolParams(validPath)).toBeNull();
795
+ });
796
+
797
+ it('should reject paths outside workspace root', () => {
798
+ const invalidPath = {
799
+ file_path: '/etc/passwd',
800
+ old_string: 'root',
801
+ new_string: 'hacked',
802
+ };
803
+ const error = tool.validateToolParams(invalidPath);
804
+ expect(error).toContain(
805
+ 'File path must be within one of the workspace directories',
806
+ );
807
+ expect(error).toContain(rootDir);
808
+ });
809
+ });
810
+
811
+ describe('IDE mode', () => {
812
+ const testFile = 'edit_me.txt';
813
+ let filePath: string;
814
+ let ideClient: any;
815
+
816
+ beforeEach(() => {
817
+ filePath = path.join(rootDir, testFile);
818
+ ideClient = {
819
+ openDiff: vi.fn(),
820
+ getConnectionStatus: vi.fn().mockReturnValue({
821
+ status: IDEConnectionStatus.Connected,
822
+ }),
823
+ };
824
+ (mockConfig as any).getIdeMode = () => true;
825
+ (mockConfig as any).getIdeClient = () => ideClient;
826
+ });
827
+
828
+ it('should call ideClient.openDiff and update params on confirmation', async () => {
829
+ const initialContent = 'some old content here';
830
+ const newContent = 'some new content here';
831
+ const modifiedContent = 'some modified content here';
832
+ fs.writeFileSync(filePath, initialContent);
833
+ const params: EditToolParams = {
834
+ file_path: filePath,
835
+ old_string: 'old',
836
+ new_string: 'new',
837
+ };
838
+ mockEnsureCorrectEdit.mockResolvedValueOnce({
839
+ params: { ...params, old_string: 'old', new_string: 'new' },
840
+ occurrences: 1,
841
+ });
842
+ ideClient.openDiff.mockResolvedValueOnce({
843
+ status: 'accepted',
844
+ content: modifiedContent,
845
+ });
846
+
847
+ const invocation = tool.build(params);
848
+ const confirmation = await invocation.shouldConfirmExecute(
849
+ new AbortController().signal,
850
+ );
851
+
852
+ expect(ideClient.openDiff).toHaveBeenCalledWith(filePath, newContent);
853
+
854
+ if (confirmation && 'onConfirm' in confirmation) {
855
+ await confirmation.onConfirm(ToolConfirmationOutcome.ProceedOnce);
856
+ }
857
+
858
+ expect(params.old_string).toBe(initialContent);
859
+ expect(params.new_string).toBe(modifiedContent);
860
+ });
861
+ });
862
+ });
projects/ui/qwen-code/packages/core/src/tools/edit.ts ADDED
@@ -0,0 +1,548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fs from 'fs';
8
+ import * as path from 'path';
9
+ import * as Diff from 'diff';
10
+ import {
11
+ BaseDeclarativeTool,
12
+ Kind,
13
+ ToolCallConfirmationDetails,
14
+ ToolConfirmationOutcome,
15
+ ToolEditConfirmationDetails,
16
+ ToolInvocation,
17
+ ToolLocation,
18
+ ToolResult,
19
+ ToolResultDisplay,
20
+ } from './tools.js';
21
+ import { ToolErrorType } from './tool-error.js';
22
+ import { makeRelative, shortenPath } from '../utils/paths.js';
23
+ import { isNodeError } from '../utils/errors.js';
24
+ import { Config, ApprovalMode } from '../config/config.js';
25
+ import { ensureCorrectEdit } from '../utils/editCorrector.js';
26
+ import { DEFAULT_DIFF_OPTIONS, getDiffStat } from './diffOptions.js';
27
+ import { ReadFileTool } from './read-file.js';
28
+ import { ModifiableDeclarativeTool, ModifyContext } from './modifiable-tool.js';
29
+ import { IDEConnectionStatus } from '../ide/ide-client.js';
30
+
31
+ export function applyReplacement(
32
+ currentContent: string | null,
33
+ oldString: string,
34
+ newString: string,
35
+ isNewFile: boolean,
36
+ ): string {
37
+ if (isNewFile) {
38
+ return newString;
39
+ }
40
+ if (currentContent === null) {
41
+ // Should not happen if not a new file, but defensively return empty or newString if oldString is also empty
42
+ return oldString === '' ? newString : '';
43
+ }
44
+ // If oldString is empty and it's not a new file, do not modify the content.
45
+ if (oldString === '' && !isNewFile) {
46
+ return currentContent;
47
+ }
48
+ return currentContent.replaceAll(oldString, newString);
49
+ }
50
+
51
+ /**
52
+ * Parameters for the Edit tool
53
+ */
54
+ export interface EditToolParams {
55
+ /**
56
+ * The absolute path to the file to modify
57
+ */
58
+ file_path: string;
59
+
60
+ /**
61
+ * The text to replace
62
+ */
63
+ old_string: string;
64
+
65
+ /**
66
+ * The text to replace it with
67
+ */
68
+ new_string: string;
69
+
70
+ /**
71
+ * Number of replacements expected. Defaults to 1 if not specified.
72
+ * Use when you want to replace multiple occurrences.
73
+ */
74
+ expected_replacements?: number;
75
+
76
+ /**
77
+ * Whether the edit was modified manually by the user.
78
+ */
79
+ modified_by_user?: boolean;
80
+
81
+ /**
82
+ * Initially proposed string.
83
+ */
84
+ ai_proposed_string?: string;
85
+ }
86
+
87
+ interface CalculatedEdit {
88
+ currentContent: string | null;
89
+ newContent: string;
90
+ occurrences: number;
91
+ error?: { display: string; raw: string; type: ToolErrorType };
92
+ isNewFile: boolean;
93
+ }
94
+
95
+ class EditToolInvocation implements ToolInvocation<EditToolParams, ToolResult> {
96
+ constructor(
97
+ private readonly config: Config,
98
+ public params: EditToolParams,
99
+ ) {}
100
+
101
+ toolLocations(): ToolLocation[] {
102
+ return [{ path: this.params.file_path }];
103
+ }
104
+
105
+ /**
106
+ * Calculates the potential outcome of an edit operation.
107
+ * @param params Parameters for the edit operation
108
+ * @returns An object describing the potential edit outcome
109
+ * @throws File system errors if reading the file fails unexpectedly (e.g., permissions)
110
+ */
111
+ private async calculateEdit(
112
+ params: EditToolParams,
113
+ abortSignal: AbortSignal,
114
+ ): Promise<CalculatedEdit> {
115
+ const expectedReplacements = params.expected_replacements ?? 1;
116
+ let currentContent: string | null = null;
117
+ let fileExists = false;
118
+ let isNewFile = false;
119
+ let finalNewString = params.new_string;
120
+ let finalOldString = params.old_string;
121
+ let occurrences = 0;
122
+ let error:
123
+ | { display: string; raw: string; type: ToolErrorType }
124
+ | undefined = undefined;
125
+
126
+ try {
127
+ currentContent = await this.config
128
+ .getFileSystemService()
129
+ .readTextFile(params.file_path);
130
+ // Normalize line endings to LF for consistent processing.
131
+ currentContent = currentContent.replace(/\r\n/g, '\n');
132
+ fileExists = true;
133
+ } catch (err: unknown) {
134
+ if (!isNodeError(err) || err.code !== 'ENOENT') {
135
+ // Rethrow unexpected FS errors (permissions, etc.)
136
+ throw err;
137
+ }
138
+ fileExists = false;
139
+ }
140
+
141
+ if (params.old_string === '' && !fileExists) {
142
+ // Creating a new file
143
+ isNewFile = true;
144
+ } else if (!fileExists) {
145
+ // Trying to edit a nonexistent file (and old_string is not empty)
146
+ error = {
147
+ display: `File not found. Cannot apply edit. Use an empty old_string to create a new file.`,
148
+ raw: `File not found: ${params.file_path}`,
149
+ type: ToolErrorType.FILE_NOT_FOUND,
150
+ };
151
+ } else if (currentContent !== null) {
152
+ // Editing an existing file
153
+ const correctedEdit = await ensureCorrectEdit(
154
+ params.file_path,
155
+ currentContent,
156
+ params,
157
+ this.config.getGeminiClient(),
158
+ abortSignal,
159
+ );
160
+ finalOldString = correctedEdit.params.old_string;
161
+ finalNewString = correctedEdit.params.new_string;
162
+ occurrences = correctedEdit.occurrences;
163
+
164
+ if (params.old_string === '') {
165
+ // Error: Trying to create a file that already exists
166
+ error = {
167
+ display: `Failed to edit. Attempted to create a file that already exists.`,
168
+ raw: `File already exists, cannot create: ${params.file_path}`,
169
+ type: ToolErrorType.ATTEMPT_TO_CREATE_EXISTING_FILE,
170
+ };
171
+ } else if (occurrences === 0) {
172
+ error = {
173
+ display: `Failed to edit, could not find the string to replace.`,
174
+ raw: `Failed to edit, 0 occurrences found for old_string in ${params.file_path}. No edits made. The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${ReadFileTool.Name} tool to verify.`,
175
+ type: ToolErrorType.EDIT_NO_OCCURRENCE_FOUND,
176
+ };
177
+ } else if (occurrences !== expectedReplacements) {
178
+ const occurrenceTerm =
179
+ expectedReplacements === 1 ? 'occurrence' : 'occurrences';
180
+
181
+ error = {
182
+ display: `Failed to edit, expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences}.`,
183
+ raw: `Failed to edit, Expected ${expectedReplacements} ${occurrenceTerm} but found ${occurrences} for old_string in file: ${params.file_path}`,
184
+ type: ToolErrorType.EDIT_EXPECTED_OCCURRENCE_MISMATCH,
185
+ };
186
+ } else if (finalOldString === finalNewString) {
187
+ error = {
188
+ display: `No changes to apply. The old_string and new_string are identical.`,
189
+ raw: `No changes to apply. The old_string and new_string are identical in file: ${params.file_path}`,
190
+ type: ToolErrorType.EDIT_NO_CHANGE,
191
+ };
192
+ }
193
+ } else {
194
+ // Should not happen if fileExists and no exception was thrown, but defensively:
195
+ error = {
196
+ display: `Failed to read content of file.`,
197
+ raw: `Failed to read content of existing file: ${params.file_path}`,
198
+ type: ToolErrorType.READ_CONTENT_FAILURE,
199
+ };
200
+ }
201
+
202
+ const newContent = applyReplacement(
203
+ currentContent,
204
+ finalOldString,
205
+ finalNewString,
206
+ isNewFile,
207
+ );
208
+
209
+ return {
210
+ currentContent,
211
+ newContent,
212
+ occurrences,
213
+ error,
214
+ isNewFile,
215
+ };
216
+ }
217
+
218
+ /**
219
+ * Handles the confirmation prompt for the Edit tool in the CLI.
220
+ * It needs to calculate the diff to show the user.
221
+ */
222
+ async shouldConfirmExecute(
223
+ abortSignal: AbortSignal,
224
+ ): Promise<ToolCallConfirmationDetails | false> {
225
+ if (this.config.getApprovalMode() === ApprovalMode.AUTO_EDIT) {
226
+ return false;
227
+ }
228
+
229
+ let editData: CalculatedEdit;
230
+ try {
231
+ editData = await this.calculateEdit(this.params, abortSignal);
232
+ } catch (error) {
233
+ const errorMsg = error instanceof Error ? error.message : String(error);
234
+ console.log(`Error preparing edit: ${errorMsg}`);
235
+ return false;
236
+ }
237
+
238
+ if (editData.error) {
239
+ console.log(`Error: ${editData.error.display}`);
240
+ return false;
241
+ }
242
+
243
+ const fileName = path.basename(this.params.file_path);
244
+ const fileDiff = Diff.createPatch(
245
+ fileName,
246
+ editData.currentContent ?? '',
247
+ editData.newContent,
248
+ 'Current',
249
+ 'Proposed',
250
+ DEFAULT_DIFF_OPTIONS,
251
+ );
252
+ const ideClient = this.config.getIdeClient();
253
+ const ideConfirmation =
254
+ this.config.getIdeMode() &&
255
+ ideClient?.getConnectionStatus().status === IDEConnectionStatus.Connected
256
+ ? ideClient.openDiff(this.params.file_path, editData.newContent)
257
+ : undefined;
258
+
259
+ const confirmationDetails: ToolEditConfirmationDetails = {
260
+ type: 'edit',
261
+ title: `Confirm Edit: ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`,
262
+ fileName,
263
+ filePath: this.params.file_path,
264
+ fileDiff,
265
+ originalContent: editData.currentContent,
266
+ newContent: editData.newContent,
267
+ onConfirm: async (outcome: ToolConfirmationOutcome) => {
268
+ if (outcome === ToolConfirmationOutcome.ProceedAlways) {
269
+ this.config.setApprovalMode(ApprovalMode.AUTO_EDIT);
270
+ }
271
+
272
+ if (ideConfirmation) {
273
+ const result = await ideConfirmation;
274
+ if (result.status === 'accepted' && result.content) {
275
+ // TODO(chrstn): See https://github.com/google-gemini/gemini-cli/pull/5618#discussion_r2255413084
276
+ // for info on a possible race condition where the file is modified on disk while being edited.
277
+ this.params.old_string = editData.currentContent ?? '';
278
+ this.params.new_string = result.content;
279
+ }
280
+ }
281
+ },
282
+ ideConfirmation,
283
+ };
284
+ return confirmationDetails;
285
+ }
286
+
287
+ getDescription(): string {
288
+ const relativePath = makeRelative(
289
+ this.params.file_path,
290
+ this.config.getTargetDir(),
291
+ );
292
+ if (this.params.old_string === '') {
293
+ return `Create ${shortenPath(relativePath)}`;
294
+ }
295
+
296
+ const oldStringSnippet =
297
+ this.params.old_string.split('\n')[0].substring(0, 30) +
298
+ (this.params.old_string.length > 30 ? '...' : '');
299
+ const newStringSnippet =
300
+ this.params.new_string.split('\n')[0].substring(0, 30) +
301
+ (this.params.new_string.length > 30 ? '...' : '');
302
+
303
+ if (this.params.old_string === this.params.new_string) {
304
+ return `No file changes to ${shortenPath(relativePath)}`;
305
+ }
306
+ return `${shortenPath(relativePath)}: ${oldStringSnippet} => ${newStringSnippet}`;
307
+ }
308
+
309
+ /**
310
+ * Executes the edit operation with the given parameters.
311
+ * @param params Parameters for the edit operation
312
+ * @returns Result of the edit operation
313
+ */
314
+ async execute(signal: AbortSignal): Promise<ToolResult> {
315
+ let editData: CalculatedEdit;
316
+ try {
317
+ editData = await this.calculateEdit(this.params, signal);
318
+ } catch (error) {
319
+ const errorMsg = error instanceof Error ? error.message : String(error);
320
+ return {
321
+ llmContent: `Error preparing edit: ${errorMsg}`,
322
+ returnDisplay: `Error preparing edit: ${errorMsg}`,
323
+ error: {
324
+ message: errorMsg,
325
+ type: ToolErrorType.EDIT_PREPARATION_FAILURE,
326
+ },
327
+ };
328
+ }
329
+
330
+ if (editData.error) {
331
+ return {
332
+ llmContent: editData.error.raw,
333
+ returnDisplay: `Error: ${editData.error.display}`,
334
+ error: {
335
+ message: editData.error.raw,
336
+ type: editData.error.type,
337
+ },
338
+ };
339
+ }
340
+
341
+ try {
342
+ this.ensureParentDirectoriesExist(this.params.file_path);
343
+ await this.config
344
+ .getFileSystemService()
345
+ .writeTextFile(this.params.file_path, editData.newContent);
346
+
347
+ let displayResult: ToolResultDisplay;
348
+ if (editData.isNewFile) {
349
+ displayResult = `Created ${shortenPath(makeRelative(this.params.file_path, this.config.getTargetDir()))}`;
350
+ } else {
351
+ // Generate diff for display, even though core logic doesn't technically need it
352
+ // The CLI wrapper will use this part of the ToolResult
353
+ const fileName = path.basename(this.params.file_path);
354
+ const fileDiff = Diff.createPatch(
355
+ fileName,
356
+ editData.currentContent ?? '', // Should not be null here if not isNewFile
357
+ editData.newContent,
358
+ 'Current',
359
+ 'Proposed',
360
+ DEFAULT_DIFF_OPTIONS,
361
+ );
362
+ const originallyProposedContent =
363
+ this.params.ai_proposed_string || this.params.new_string;
364
+ const diffStat = getDiffStat(
365
+ fileName,
366
+ editData.currentContent ?? '',
367
+ originallyProposedContent,
368
+ this.params.new_string,
369
+ );
370
+ displayResult = {
371
+ fileDiff,
372
+ fileName,
373
+ originalContent: editData.currentContent,
374
+ newContent: editData.newContent,
375
+ diffStat,
376
+ };
377
+ }
378
+
379
+ const llmSuccessMessageParts = [
380
+ editData.isNewFile
381
+ ? `Created new file: ${this.params.file_path} with provided content.`
382
+ : `Successfully modified file: ${this.params.file_path} (${editData.occurrences} replacements).`,
383
+ ];
384
+ if (this.params.modified_by_user) {
385
+ llmSuccessMessageParts.push(
386
+ `User modified the \`new_string\` content to be: ${this.params.new_string}.`,
387
+ );
388
+ }
389
+
390
+ return {
391
+ llmContent: llmSuccessMessageParts.join(' '),
392
+ returnDisplay: displayResult,
393
+ };
394
+ } catch (error) {
395
+ const errorMsg = error instanceof Error ? error.message : String(error);
396
+ return {
397
+ llmContent: `Error executing edit: ${errorMsg}`,
398
+ returnDisplay: `Error writing file: ${errorMsg}`,
399
+ error: {
400
+ message: errorMsg,
401
+ type: ToolErrorType.FILE_WRITE_FAILURE,
402
+ },
403
+ };
404
+ }
405
+ }
406
+
407
+ /**
408
+ * Creates parent directories if they don't exist
409
+ */
410
+ private ensureParentDirectoriesExist(filePath: string): void {
411
+ const dirName = path.dirname(filePath);
412
+ if (!fs.existsSync(dirName)) {
413
+ fs.mkdirSync(dirName, { recursive: true });
414
+ }
415
+ }
416
+ }
417
+
418
+ /**
419
+ * Implementation of the Edit tool logic
420
+ */
421
+ export class EditTool
422
+ extends BaseDeclarativeTool<EditToolParams, ToolResult>
423
+ implements ModifiableDeclarativeTool<EditToolParams>
424
+ {
425
+ static readonly Name = 'replace';
426
+ constructor(private readonly config: Config) {
427
+ super(
428
+ EditTool.Name,
429
+ 'Edit',
430
+ `Replaces text within a file. By default, replaces a single occurrence, but can replace multiple occurrences when \`expected_replacements\` is specified. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${ReadFileTool.Name} tool to examine the file's current content before attempting a text replacement.
431
+
432
+ The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
433
+
434
+ Expectation for required parameters:
435
+ 1. \`file_path\` MUST be an absolute path; otherwise an error will be thrown.
436
+ 2. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.).
437
+ 3. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic.
438
+ 4. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
439
+ **Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
440
+ **Multiple replacements:** Set \`expected_replacements\` to the number of occurrences you want to replace. The tool will replace ALL occurrences that match \`old_string\` exactly. Ensure the number of replacements matches your expectation.`,
441
+ Kind.Edit,
442
+ {
443
+ properties: {
444
+ file_path: {
445
+ description:
446
+ "The absolute path to the file to modify. Must start with '/'.",
447
+ type: 'string',
448
+ },
449
+ old_string: {
450
+ description:
451
+ 'The exact literal text to replace, preferably unescaped. For single replacements (default), include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. For multiple replacements, specify expected_replacements parameter. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail.',
452
+ type: 'string',
453
+ },
454
+ new_string: {
455
+ description:
456
+ 'The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.',
457
+ type: 'string',
458
+ },
459
+ expected_replacements: {
460
+ type: 'number',
461
+ description:
462
+ 'Number of replacements expected. Defaults to 1 if not specified. Use when you want to replace multiple occurrences.',
463
+ minimum: 1,
464
+ },
465
+ },
466
+ required: ['file_path', 'old_string', 'new_string'],
467
+ type: 'object',
468
+ },
469
+ );
470
+ }
471
+
472
+ /**
473
+ * Validates the parameters for the Edit tool
474
+ * @param params Parameters to validate
475
+ * @returns Error message string or null if valid
476
+ */
477
+ protected override validateToolParamValues(
478
+ params: EditToolParams,
479
+ ): string | null {
480
+ if (!params.file_path) {
481
+ return "The 'file_path' parameter must be non-empty.";
482
+ }
483
+
484
+ if (!path.isAbsolute(params.file_path)) {
485
+ return `File path must be absolute: ${params.file_path}`;
486
+ }
487
+
488
+ const workspaceContext = this.config.getWorkspaceContext();
489
+ if (!workspaceContext.isPathWithinWorkspace(params.file_path)) {
490
+ const directories = workspaceContext.getDirectories();
491
+ return `File path must be within one of the workspace directories: ${directories.join(', ')}`;
492
+ }
493
+
494
+ return null;
495
+ }
496
+
497
+ protected createInvocation(
498
+ params: EditToolParams,
499
+ ): ToolInvocation<EditToolParams, ToolResult> {
500
+ return new EditToolInvocation(this.config, params);
501
+ }
502
+
503
+ getModifyContext(_: AbortSignal): ModifyContext<EditToolParams> {
504
+ return {
505
+ getFilePath: (params: EditToolParams) => params.file_path,
506
+ getCurrentContent: async (params: EditToolParams): Promise<string> => {
507
+ try {
508
+ return this.config
509
+ .getFileSystemService()
510
+ .readTextFile(params.file_path);
511
+ } catch (err) {
512
+ if (!isNodeError(err) || err.code !== 'ENOENT') throw err;
513
+ return '';
514
+ }
515
+ },
516
+ getProposedContent: async (params: EditToolParams): Promise<string> => {
517
+ try {
518
+ const currentContent = await this.config
519
+ .getFileSystemService()
520
+ .readTextFile(params.file_path);
521
+ return applyReplacement(
522
+ currentContent,
523
+ params.old_string,
524
+ params.new_string,
525
+ params.old_string === '' && currentContent === '',
526
+ );
527
+ } catch (err) {
528
+ if (!isNodeError(err) || err.code !== 'ENOENT') throw err;
529
+ return '';
530
+ }
531
+ },
532
+ createUpdatedParams: (
533
+ oldContent: string,
534
+ modifiedProposedContent: string,
535
+ originalParams: EditToolParams,
536
+ ): EditToolParams => {
537
+ const content = originalParams.new_string;
538
+ return {
539
+ ...originalParams,
540
+ ai_proposed_string: content,
541
+ old_string: oldContent,
542
+ new_string: modifiedProposedContent,
543
+ modified_by_user: true,
544
+ };
545
+ },
546
+ };
547
+ }
548
+ }
projects/ui/qwen-code/packages/core/src/tools/glob.test.ts ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { GlobTool, GlobToolParams, GlobPath, sortFileEntries } from './glob.js';
8
+ import { partListUnionToString } from '../core/geminiRequest.js';
9
+ import path from 'path';
10
+ import fs from 'fs/promises';
11
+ import os from 'os';
12
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
13
+ import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
14
+ import { Config } from '../config/config.js';
15
+ import { createMockWorkspaceContext } from '../test-utils/mockWorkspaceContext.js';
16
+
17
+ describe('GlobTool', () => {
18
+ let tempRootDir: string; // This will be the rootDirectory for the GlobTool instance
19
+ let globTool: GlobTool;
20
+ const abortSignal = new AbortController().signal;
21
+
22
+ // Mock config for testing
23
+ const mockConfig = {
24
+ getFileService: () => new FileDiscoveryService(tempRootDir),
25
+ getFileFilteringRespectGitIgnore: () => true,
26
+ getTargetDir: () => tempRootDir,
27
+ getWorkspaceContext: () => createMockWorkspaceContext(tempRootDir),
28
+ } as unknown as Config;
29
+
30
+ beforeEach(async () => {
31
+ // Create a unique root directory for each test run
32
+ tempRootDir = await fs.mkdtemp(path.join(os.tmpdir(), 'glob-tool-root-'));
33
+ globTool = new GlobTool(mockConfig);
34
+
35
+ // Create some test files and directories within this root
36
+ // Top-level files
37
+ await fs.writeFile(path.join(tempRootDir, 'fileA.txt'), 'contentA');
38
+ await fs.writeFile(path.join(tempRootDir, 'FileB.TXT'), 'contentB'); // Different case for testing
39
+
40
+ // Subdirectory and files within it
41
+ await fs.mkdir(path.join(tempRootDir, 'sub'));
42
+ await fs.writeFile(path.join(tempRootDir, 'sub', 'fileC.md'), 'contentC');
43
+ await fs.writeFile(path.join(tempRootDir, 'sub', 'FileD.MD'), 'contentD'); // Different case
44
+
45
+ // Deeper subdirectory
46
+ await fs.mkdir(path.join(tempRootDir, 'sub', 'deep'));
47
+ await fs.writeFile(
48
+ path.join(tempRootDir, 'sub', 'deep', 'fileE.log'),
49
+ 'contentE',
50
+ );
51
+
52
+ // Files for mtime sorting test
53
+ await fs.writeFile(path.join(tempRootDir, 'older.sortme'), 'older_content');
54
+ // Ensure a noticeable difference in modification time
55
+ await new Promise((resolve) => setTimeout(resolve, 50));
56
+ await fs.writeFile(path.join(tempRootDir, 'newer.sortme'), 'newer_content');
57
+ });
58
+
59
+ afterEach(async () => {
60
+ // Clean up the temporary root directory
61
+ await fs.rm(tempRootDir, { recursive: true, force: true });
62
+ });
63
+
64
+ describe('execute', () => {
65
+ it('should find files matching a simple pattern in the root', async () => {
66
+ const params: GlobToolParams = { pattern: '*.txt' };
67
+ const invocation = globTool.build(params);
68
+ const result = await invocation.execute(abortSignal);
69
+ expect(result.llmContent).toContain('Found 2 file(s)');
70
+ expect(result.llmContent).toContain(path.join(tempRootDir, 'fileA.txt'));
71
+ expect(result.llmContent).toContain(path.join(tempRootDir, 'FileB.TXT'));
72
+ expect(result.returnDisplay).toBe('Found 2 matching file(s)');
73
+ });
74
+
75
+ it('should find files case-sensitively when case_sensitive is true', async () => {
76
+ const params: GlobToolParams = { pattern: '*.txt', case_sensitive: true };
77
+ const invocation = globTool.build(params);
78
+ const result = await invocation.execute(abortSignal);
79
+ expect(result.llmContent).toContain('Found 1 file(s)');
80
+ expect(result.llmContent).toContain(path.join(tempRootDir, 'fileA.txt'));
81
+ expect(result.llmContent).not.toContain(
82
+ path.join(tempRootDir, 'FileB.TXT'),
83
+ );
84
+ });
85
+
86
+ it('should find files case-insensitively by default (pattern: *.TXT)', async () => {
87
+ const params: GlobToolParams = { pattern: '*.TXT' };
88
+ const invocation = globTool.build(params);
89
+ const result = await invocation.execute(abortSignal);
90
+ expect(result.llmContent).toContain('Found 2 file(s)');
91
+ expect(result.llmContent).toContain(path.join(tempRootDir, 'fileA.txt'));
92
+ expect(result.llmContent).toContain(path.join(tempRootDir, 'FileB.TXT'));
93
+ });
94
+
95
+ it('should find files case-insensitively when case_sensitive is false (pattern: *.TXT)', async () => {
96
+ const params: GlobToolParams = {
97
+ pattern: '*.TXT',
98
+ case_sensitive: false,
99
+ };
100
+ const invocation = globTool.build(params);
101
+ const result = await invocation.execute(abortSignal);
102
+ expect(result.llmContent).toContain('Found 2 file(s)');
103
+ expect(result.llmContent).toContain(path.join(tempRootDir, 'fileA.txt'));
104
+ expect(result.llmContent).toContain(path.join(tempRootDir, 'FileB.TXT'));
105
+ });
106
+
107
+ it('should find files using a pattern that includes a subdirectory', async () => {
108
+ const params: GlobToolParams = { pattern: 'sub/*.md' };
109
+ const invocation = globTool.build(params);
110
+ const result = await invocation.execute(abortSignal);
111
+ expect(result.llmContent).toContain('Found 2 file(s)');
112
+ expect(result.llmContent).toContain(
113
+ path.join(tempRootDir, 'sub', 'fileC.md'),
114
+ );
115
+ expect(result.llmContent).toContain(
116
+ path.join(tempRootDir, 'sub', 'FileD.MD'),
117
+ );
118
+ });
119
+
120
+ it('should find files in a specified relative path (relative to rootDir)', async () => {
121
+ const params: GlobToolParams = { pattern: '*.md', path: 'sub' };
122
+ const invocation = globTool.build(params);
123
+ const result = await invocation.execute(abortSignal);
124
+ expect(result.llmContent).toContain('Found 2 file(s)');
125
+ expect(result.llmContent).toContain(
126
+ path.join(tempRootDir, 'sub', 'fileC.md'),
127
+ );
128
+ expect(result.llmContent).toContain(
129
+ path.join(tempRootDir, 'sub', 'FileD.MD'),
130
+ );
131
+ });
132
+
133
+ it('should find files using a deep globstar pattern (e.g., **/*.log)', async () => {
134
+ const params: GlobToolParams = { pattern: '**/*.log' };
135
+ const invocation = globTool.build(params);
136
+ const result = await invocation.execute(abortSignal);
137
+ expect(result.llmContent).toContain('Found 1 file(s)');
138
+ expect(result.llmContent).toContain(
139
+ path.join(tempRootDir, 'sub', 'deep', 'fileE.log'),
140
+ );
141
+ });
142
+
143
+ it('should return "No files found" message when pattern matches nothing', async () => {
144
+ const params: GlobToolParams = { pattern: '*.nonexistent' };
145
+ const invocation = globTool.build(params);
146
+ const result = await invocation.execute(abortSignal);
147
+ expect(result.llmContent).toContain(
148
+ 'No files found matching pattern "*.nonexistent"',
149
+ );
150
+ expect(result.returnDisplay).toBe('No files found');
151
+ });
152
+
153
+ it('should find files with special characters in the name', async () => {
154
+ await fs.writeFile(path.join(tempRootDir, 'file[1].txt'), 'content');
155
+ const params: GlobToolParams = { pattern: 'file[1].txt' };
156
+ const invocation = globTool.build(params);
157
+ const result = await invocation.execute(abortSignal);
158
+ expect(result.llmContent).toContain('Found 1 file(s)');
159
+ expect(result.llmContent).toContain(
160
+ path.join(tempRootDir, 'file[1].txt'),
161
+ );
162
+ });
163
+
164
+ it('should find files with special characters like [] and () in the path', async () => {
165
+ const filePath = path.join(
166
+ tempRootDir,
167
+ 'src/app/[test]/(dashboard)/testing/components/code.tsx',
168
+ );
169
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
170
+ await fs.writeFile(filePath, 'content');
171
+
172
+ const params: GlobToolParams = {
173
+ pattern: 'src/app/[test]/(dashboard)/testing/components/code.tsx',
174
+ };
175
+ const invocation = globTool.build(params);
176
+ const result = await invocation.execute(abortSignal);
177
+ expect(result.llmContent).toContain('Found 1 file(s)');
178
+ expect(result.llmContent).toContain(filePath);
179
+ });
180
+
181
+ it('should correctly sort files by modification time (newest first)', async () => {
182
+ const params: GlobToolParams = { pattern: '*.sortme' };
183
+ const invocation = globTool.build(params);
184
+ const result = await invocation.execute(abortSignal);
185
+ const llmContent = partListUnionToString(result.llmContent);
186
+
187
+ expect(llmContent).toContain('Found 2 file(s)');
188
+ // Ensure llmContent is a string for TypeScript type checking
189
+ expect(typeof llmContent).toBe('string');
190
+
191
+ const filesListed = llmContent
192
+ .trim()
193
+ .split(/\r?\n/)
194
+ .slice(1)
195
+ .map((line) => line.trim())
196
+ .filter(Boolean);
197
+
198
+ expect(filesListed).toHaveLength(2);
199
+ expect(path.resolve(filesListed[0])).toBe(
200
+ path.resolve(tempRootDir, 'newer.sortme'),
201
+ );
202
+ expect(path.resolve(filesListed[1])).toBe(
203
+ path.resolve(tempRootDir, 'older.sortme'),
204
+ );
205
+ });
206
+ });
207
+
208
+ describe('validateToolParams', () => {
209
+ it('should return null for valid parameters (pattern only)', () => {
210
+ const params: GlobToolParams = { pattern: '*.js' };
211
+ expect(globTool.validateToolParams(params)).toBeNull();
212
+ });
213
+
214
+ it('should return null for valid parameters (pattern and path)', () => {
215
+ const params: GlobToolParams = { pattern: '*.js', path: 'sub' };
216
+ expect(globTool.validateToolParams(params)).toBeNull();
217
+ });
218
+
219
+ it('should return null for valid parameters (pattern, path, and case_sensitive)', () => {
220
+ const params: GlobToolParams = {
221
+ pattern: '*.js',
222
+ path: 'sub',
223
+ case_sensitive: true,
224
+ };
225
+ expect(globTool.validateToolParams(params)).toBeNull();
226
+ });
227
+
228
+ it('should return error if pattern is missing (schema validation)', () => {
229
+ // Need to correctly define this as an object without pattern
230
+ const params = { path: '.' };
231
+ // @ts-expect-error - We're intentionally creating invalid params for testing
232
+ expect(globTool.validateToolParams(params)).toBe(
233
+ `params must have required property 'pattern'`,
234
+ );
235
+ });
236
+
237
+ it('should return error if pattern is an empty string', () => {
238
+ const params: GlobToolParams = { pattern: '' };
239
+ expect(globTool.validateToolParams(params)).toContain(
240
+ "The 'pattern' parameter cannot be empty.",
241
+ );
242
+ });
243
+
244
+ it('should return error if pattern is only whitespace', () => {
245
+ const params: GlobToolParams = { pattern: ' ' };
246
+ expect(globTool.validateToolParams(params)).toContain(
247
+ "The 'pattern' parameter cannot be empty.",
248
+ );
249
+ });
250
+
251
+ it('should return error if path is provided but is not a string (schema validation)', () => {
252
+ const params = {
253
+ pattern: '*.ts',
254
+ path: 123,
255
+ };
256
+ // @ts-expect-error - We're intentionally creating invalid params for testing
257
+ expect(globTool.validateToolParams(params)).toBe(
258
+ 'params/path must be string',
259
+ );
260
+ });
261
+
262
+ it('should return error if case_sensitive is provided but is not a boolean (schema validation)', () => {
263
+ const params = {
264
+ pattern: '*.ts',
265
+ case_sensitive: 'true',
266
+ };
267
+ // @ts-expect-error - We're intentionally creating invalid params for testing
268
+ expect(globTool.validateToolParams(params)).toBe(
269
+ 'params/case_sensitive must be boolean',
270
+ );
271
+ });
272
+
273
+ it("should return error if search path resolves outside the tool's root directory", () => {
274
+ // Create a globTool instance specifically for this test, with a deeper root
275
+ tempRootDir = path.join(tempRootDir, 'sub');
276
+ const specificGlobTool = new GlobTool(mockConfig);
277
+ // const params: GlobToolParams = { pattern: '*.txt', path: '..' }; // This line is unused and will be removed.
278
+ // This should be fine as tempRootDir is still within the original tempRootDir (the parent of deeperRootDir)
279
+ // Let's try to go further up.
280
+ const paramsOutside: GlobToolParams = {
281
+ pattern: '*.txt',
282
+ path: '../../../../../../../../../../tmp', // Definitely outside
283
+ };
284
+ expect(specificGlobTool.validateToolParams(paramsOutside)).toContain(
285
+ 'resolves outside the allowed workspace directories',
286
+ );
287
+ });
288
+
289
+ it('should return error if specified search path does not exist', async () => {
290
+ const params: GlobToolParams = {
291
+ pattern: '*.txt',
292
+ path: 'nonexistent_subdir',
293
+ };
294
+ expect(globTool.validateToolParams(params)).toContain(
295
+ 'Search path does not exist',
296
+ );
297
+ });
298
+
299
+ it('should return error if specified search path is a file, not a directory', async () => {
300
+ const params: GlobToolParams = { pattern: '*.txt', path: 'fileA.txt' };
301
+ expect(globTool.validateToolParams(params)).toContain(
302
+ 'Search path is not a directory',
303
+ );
304
+ });
305
+ });
306
+
307
+ describe('workspace boundary validation', () => {
308
+ it('should validate search paths are within workspace boundaries', () => {
309
+ const validPath = { pattern: '*.ts', path: 'sub' };
310
+ const invalidPath = { pattern: '*.ts', path: '../..' };
311
+
312
+ expect(globTool.validateToolParams(validPath)).toBeNull();
313
+ expect(globTool.validateToolParams(invalidPath)).toContain(
314
+ 'resolves outside the allowed workspace directories',
315
+ );
316
+ });
317
+
318
+ it('should provide clear error messages when path is outside workspace', () => {
319
+ const invalidPath = { pattern: '*.ts', path: '/etc' };
320
+ const error = globTool.validateToolParams(invalidPath);
321
+
322
+ expect(error).toContain(
323
+ 'resolves outside the allowed workspace directories',
324
+ );
325
+ expect(error).toContain(tempRootDir);
326
+ });
327
+
328
+ it('should work with paths in workspace subdirectories', async () => {
329
+ const params: GlobToolParams = { pattern: '*.md', path: 'sub' };
330
+ const invocation = globTool.build(params);
331
+ const result = await invocation.execute(abortSignal);
332
+
333
+ expect(result.llmContent).toContain('Found 2 file(s)');
334
+ expect(result.llmContent).toContain('fileC.md');
335
+ expect(result.llmContent).toContain('FileD.MD');
336
+ });
337
+ });
338
+ });
339
+
340
+ describe('sortFileEntries', () => {
341
+ const nowTimestamp = new Date('2024-01-15T12:00:00.000Z').getTime();
342
+ const oneDayInMs = 24 * 60 * 60 * 1000;
343
+
344
+ const createFileEntry = (fullpath: string, mtimeDate: Date): GlobPath => ({
345
+ fullpath: () => fullpath,
346
+ mtimeMs: mtimeDate.getTime(),
347
+ });
348
+
349
+ it('should sort a mix of recent and older files correctly', () => {
350
+ const recentTime1 = new Date(nowTimestamp - 1 * 60 * 60 * 1000); // 1 hour ago
351
+ const recentTime2 = new Date(nowTimestamp - 2 * 60 * 60 * 1000); // 2 hours ago
352
+ const olderTime1 = new Date(
353
+ nowTimestamp - (oneDayInMs + 1 * 60 * 60 * 1000),
354
+ ); // 25 hours ago
355
+ const olderTime2 = new Date(
356
+ nowTimestamp - (oneDayInMs + 2 * 60 * 60 * 1000),
357
+ ); // 26 hours ago
358
+
359
+ const entries: GlobPath[] = [
360
+ createFileEntry('older_zebra.txt', olderTime2),
361
+ createFileEntry('recent_alpha.txt', recentTime1),
362
+ createFileEntry('older_apple.txt', olderTime1),
363
+ createFileEntry('recent_beta.txt', recentTime2),
364
+ createFileEntry('older_banana.txt', olderTime1), // Same mtime as apple
365
+ ];
366
+
367
+ const sorted = sortFileEntries(entries, nowTimestamp, oneDayInMs);
368
+ const sortedPaths = sorted.map((e) => e.fullpath());
369
+
370
+ expect(sortedPaths).toEqual([
371
+ 'recent_alpha.txt', // Recent, newest
372
+ 'recent_beta.txt', // Recent, older
373
+ 'older_apple.txt', // Older, alphabetical
374
+ 'older_banana.txt', // Older, alphabetical
375
+ 'older_zebra.txt', // Older, alphabetical
376
+ ]);
377
+ });
378
+
379
+ it('should sort only recent files by mtime descending', () => {
380
+ const recentTime1 = new Date(nowTimestamp - 1000); // Newest
381
+ const recentTime2 = new Date(nowTimestamp - 2000);
382
+ const recentTime3 = new Date(nowTimestamp - 3000); // Oldest recent
383
+
384
+ const entries: GlobPath[] = [
385
+ createFileEntry('c.txt', recentTime2),
386
+ createFileEntry('a.txt', recentTime3),
387
+ createFileEntry('b.txt', recentTime1),
388
+ ];
389
+ const sorted = sortFileEntries(entries, nowTimestamp, oneDayInMs);
390
+ expect(sorted.map((e) => e.fullpath())).toEqual([
391
+ 'b.txt',
392
+ 'c.txt',
393
+ 'a.txt',
394
+ ]);
395
+ });
396
+
397
+ it('should sort only older files alphabetically by path', () => {
398
+ const olderTime = new Date(nowTimestamp - 2 * oneDayInMs); // All equally old
399
+ const entries: GlobPath[] = [
400
+ createFileEntry('zebra.txt', olderTime),
401
+ createFileEntry('apple.txt', olderTime),
402
+ createFileEntry('banana.txt', olderTime),
403
+ ];
404
+ const sorted = sortFileEntries(entries, nowTimestamp, oneDayInMs);
405
+ expect(sorted.map((e) => e.fullpath())).toEqual([
406
+ 'apple.txt',
407
+ 'banana.txt',
408
+ 'zebra.txt',
409
+ ]);
410
+ });
411
+
412
+ it('should handle an empty array', () => {
413
+ const entries: GlobPath[] = [];
414
+ const sorted = sortFileEntries(entries, nowTimestamp, oneDayInMs);
415
+ expect(sorted).toEqual([]);
416
+ });
417
+
418
+ it('should correctly sort files when mtimes are identical for older files', () => {
419
+ const olderTime = new Date(nowTimestamp - 2 * oneDayInMs);
420
+ const entries: GlobPath[] = [
421
+ createFileEntry('b.txt', olderTime),
422
+ createFileEntry('a.txt', olderTime),
423
+ ];
424
+ const sorted = sortFileEntries(entries, nowTimestamp, oneDayInMs);
425
+ expect(sorted.map((e) => e.fullpath())).toEqual(['a.txt', 'b.txt']);
426
+ });
427
+
428
+ it('should correctly sort files when mtimes are identical for recent files (maintaining mtime sort)', () => {
429
+ const recentTime = new Date(nowTimestamp - 1000);
430
+ const entries: GlobPath[] = [
431
+ createFileEntry('b.txt', recentTime),
432
+ createFileEntry('a.txt', recentTime),
433
+ ];
434
+ const sorted = sortFileEntries(entries, nowTimestamp, oneDayInMs);
435
+ expect(sorted.map((e) => e.fullpath())).toContain('a.txt');
436
+ expect(sorted.map((e) => e.fullpath())).toContain('b.txt');
437
+ expect(sorted.length).toBe(2);
438
+ });
439
+
440
+ it('should use recencyThresholdMs parameter correctly', () => {
441
+ const justOverThreshold = new Date(nowTimestamp - (1000 + 1)); // Barely older
442
+ const justUnderThreshold = new Date(nowTimestamp - (1000 - 1)); // Barely recent
443
+ const customThresholdMs = 1000; // 1 second
444
+
445
+ const entries: GlobPath[] = [
446
+ createFileEntry('older_file.txt', justOverThreshold),
447
+ createFileEntry('recent_file.txt', justUnderThreshold),
448
+ ];
449
+ const sorted = sortFileEntries(entries, nowTimestamp, customThresholdMs);
450
+ expect(sorted.map((e) => e.fullpath())).toEqual([
451
+ 'recent_file.txt',
452
+ 'older_file.txt',
453
+ ]);
454
+ });
455
+ });