File size: 8,439 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach, type Mock } from 'vitest';
import { ToolModificationHandler } from './tool-modifier.js';
import {
  CoreToolCallStatus,
  type WaitingToolCall,
  type ToolCallRequestInfo,
} from './types.js';
import * as modifiableToolModule from '../tools/modifiable-tool.js';
import type { ModifyContext } from '../tools/modifiable-tool.js';
import * as Diff from 'diff';
import { MockModifiableTool, MockTool } from '../test-utils/mock-tool.js';
import type {
  ToolResult,
  ToolInvocation,
  ToolConfirmationPayload,
} from '../tools/tools.js';

// Mock the modules that export functions we need to control
vi.mock('diff', () => ({
  createPatch: vi.fn(),
  diffLines: vi.fn(),
}));

vi.mock('../tools/modifiable-tool.js', () => ({
  isModifiableDeclarativeTool: vi.fn(),
  modifyWithEditor: vi.fn(),
}));

type MockModifyContext = {
  [K in keyof ModifyContext<Record<string, unknown>>]: Mock;
};

function createMockWaitingToolCall(
  overrides: Partial<WaitingToolCall> = {},
): WaitingToolCall {
  return {
    status: CoreToolCallStatus.AwaitingApproval,
    request: {
      callId: 'test-call-id',
      name: 'test-tool',
      args: {},
      isClientInitiated: false,
      prompt_id: 'test-prompt-id',
    } as ToolCallRequestInfo,
    tool: new MockTool({ name: 'test-tool' }),
    invocation: {} as ToolInvocation<Record<string, unknown>, ToolResult>, // We generally don't check invocation details in these tests
    confirmationDetails: {
      type: 'edit',
      title: 'Test Confirmation',
      fileName: 'test.txt',
      filePath: '/path/to/test.txt',
      fileDiff: 'diff',
      originalContent: 'original',
      newContent: 'new',
      onConfirm: async () => {},
    },
    ...overrides,
  };
}

describe('ToolModificationHandler', () => {
  let handler: ToolModificationHandler;
  let mockModifiableTool: MockModifiableTool;
  let mockPlainTool: MockTool;
  let mockModifyContext: MockModifyContext;

  beforeEach(() => {
    vi.clearAllMocks();
    handler = new ToolModificationHandler();
    mockModifiableTool = new MockModifiableTool();
    mockPlainTool = new MockTool({ name: 'plainTool' });

    mockModifyContext = {
      getCurrentContent: vi.fn(),
      getFilePath: vi.fn(),
      createUpdatedParams: vi.fn(),
      getProposedContent: vi.fn(),
    };

    vi.spyOn(mockModifiableTool, 'getModifyContext').mockReturnValue(
      mockModifyContext as unknown as ModifyContext<Record<string, unknown>>,
    );
  });

  describe('handleModifyWithEditor', () => {
    it('should return undefined if tool is not modifiable', async () => {
      vi.mocked(
        modifiableToolModule.isModifiableDeclarativeTool,
      ).mockReturnValue(false);

      const mockWaitingToolCall = createMockWaitingToolCall({
        tool: mockPlainTool,
        request: {
          callId: 'call-1',
          name: 'plainTool',
          args: { path: 'foo.txt' },
          isClientInitiated: false,
          prompt_id: 'p1',
        },
      });

      const result = await handler.handleModifyWithEditor(
        mockWaitingToolCall,
        'vscode',
        new AbortController().signal,
      );

      expect(result).toBeUndefined();
    });

    it('should call modifyWithEditor and return updated params', async () => {
      vi.mocked(
        modifiableToolModule.isModifiableDeclarativeTool,
      ).mockReturnValue(true);

      vi.mocked(modifiableToolModule.modifyWithEditor).mockResolvedValue({
        updatedParams: { path: 'foo.txt', content: 'new' },
        updatedDiff: 'diff',
      });

      const mockWaitingToolCall = createMockWaitingToolCall({
        tool: mockModifiableTool,
        request: {
          callId: 'call-1',
          name: 'mockModifiableTool',
          args: { path: 'foo.txt' },
          isClientInitiated: false,
          prompt_id: 'p1',
        },
        confirmationDetails: {
          type: 'edit',
          title: 'Confirm',
          fileName: 'foo.txt',
          filePath: 'foo.txt',
          fileDiff: 'diff',
          originalContent: 'old',
          newContent: 'new',
          onConfirm: async () => {},
        },
      });

      const result = await handler.handleModifyWithEditor(
        mockWaitingToolCall,
        'vscode',
        new AbortController().signal,
      );

      expect(modifiableToolModule.modifyWithEditor).toHaveBeenCalledWith(
        mockWaitingToolCall.request.args,
        mockModifyContext,
        'vscode',
        expect.any(AbortSignal),
        { currentContent: 'old', proposedContent: 'new' },
      );

      expect(result).toEqual({
        updatedParams: { path: 'foo.txt', content: 'new' },
        updatedDiff: 'diff',
      });
    });
  });

  describe('applyInlineModify', () => {
    it('should return undefined if tool is not modifiable', async () => {
      vi.mocked(
        modifiableToolModule.isModifiableDeclarativeTool,
      ).mockReturnValue(false);

      const mockWaitingToolCall = createMockWaitingToolCall({
        tool: mockPlainTool,
      });

      const result = await handler.applyInlineModify(
        mockWaitingToolCall,
        { newContent: 'foo' },
        new AbortController().signal,
      );

      expect(result).toBeUndefined();
    });

    it('should return undefined if payload has no new content', async () => {
      vi.mocked(
        modifiableToolModule.isModifiableDeclarativeTool,
      ).mockReturnValue(true);

      const mockWaitingToolCall = createMockWaitingToolCall({
        tool: mockModifiableTool,
      });

      const result = await handler.applyInlineModify(
        mockWaitingToolCall,
        {} as ToolConfirmationPayload, // no newContent property
        new AbortController().signal,
      );

      expect(result).toBeUndefined();
    });

    it('should process empty string as valid new content', async () => {
      vi.mocked(
        modifiableToolModule.isModifiableDeclarativeTool,
      ).mockReturnValue(true);
      (Diff.createPatch as unknown as Mock).mockReturnValue('mock-diff-empty');

      mockModifyContext.getCurrentContent.mockResolvedValue('old content');
      mockModifyContext.getFilePath.mockReturnValue('test.txt');
      mockModifyContext.createUpdatedParams.mockReturnValue({
        content: '',
      });

      const mockWaitingToolCall = createMockWaitingToolCall({
        tool: mockModifiableTool,
      });

      const result = await handler.applyInlineModify(
        mockWaitingToolCall,
        { newContent: '' },
        new AbortController().signal,
      );

      expect(mockModifyContext.createUpdatedParams).toHaveBeenCalledWith(
        expect.any(String),
        '',
        expect.any(Object),
      );
      expect(result).toEqual({
        updatedParams: { content: '' },
        updatedDiff: 'mock-diff-empty',
      });
    });

    it('should calculate diff and return updated params', async () => {
      vi.mocked(
        modifiableToolModule.isModifiableDeclarativeTool,
      ).mockReturnValue(true);
      (Diff.createPatch as unknown as Mock).mockReturnValue('mock-diff');

      mockModifyContext.getCurrentContent.mockResolvedValue('old content');
      mockModifyContext.getFilePath.mockReturnValue('test.txt');
      mockModifyContext.createUpdatedParams.mockReturnValue({
        content: 'new content',
      });

      const mockWaitingToolCall = createMockWaitingToolCall({
        tool: mockModifiableTool,
        request: {
          callId: 'call-1',
          name: 'mockModifiableTool',
          args: { content: 'original' },
          isClientInitiated: false,
          prompt_id: 'p1',
        },
      });

      const result = await handler.applyInlineModify(
        mockWaitingToolCall,
        { newContent: 'new content' },
        new AbortController().signal,
      );

      expect(mockModifyContext.getCurrentContent).toHaveBeenCalled();
      expect(mockModifyContext.createUpdatedParams).toHaveBeenCalledWith(
        'old content',
        'new content',
        { content: 'original' },
      );
      expect(Diff.createPatch).toHaveBeenCalledWith(
        'test.txt',
        'old content',
        'new content',
        'Current',
        'Proposed',
      );

      expect(result).toEqual({
        updatedParams: { content: 'new content' },
        updatedDiff: 'mock-diff',
      });
    });
  });
});