This repository was archived by the owner on May 15, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Expand file tree
/
Copy pathwriteToFileTool.spec.ts
More file actions
430 lines (352 loc) · 14 KB
/
Copy pathwriteToFileTool.spec.ts
File metadata and controls
430 lines (352 loc) · 14 KB
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
import * as path from "path"
import type { MockedFunction } from "vitest"
import { fileExistsAtPath, createDirectoriesForFile } from "../../../utils/fs"
import { isPathOutsideWorkspace } from "../../../utils/pathUtils"
import { getReadablePath } from "../../../utils/path"
import { everyLineHasLineNumbers, stripLineNumbers } from "../../../integrations/misc/extract-text"
import { ToolUse, ToolResponse } from "../../../shared/tools"
import { writeToFileTool } from "../WriteToFileTool"
vi.mock("path", async () => {
const originalPath = await vi.importActual("path")
return {
...originalPath,
resolve: vi.fn().mockImplementation((...args) => {
// On Windows, use backslashes; on Unix, use forward slashes
const separator = process.platform === "win32" ? "\\" : "/"
return args.join(separator)
}),
}
})
vi.mock("delay", () => ({
default: vi.fn(),
}))
vi.mock("../../../utils/fs", () => ({
fileExistsAtPath: vi.fn().mockResolvedValue(false),
createDirectoriesForFile: vi.fn().mockResolvedValue([]),
}))
vi.mock("../../prompts/responses", () => ({
formatResponse: {
toolError: vi.fn((msg) => `Error: ${msg}`),
rooIgnoreError: vi.fn((path) => `Access denied: ${path}`),
createPrettyPatch: vi.fn(() => "mock-diff"),
},
}))
vi.mock("../../../utils/pathUtils", () => ({
isPathOutsideWorkspace: vi.fn().mockReturnValue(false),
}))
vi.mock("../../../utils/path", () => ({
getReadablePath: vi.fn().mockReturnValue("test/path.txt"),
}))
vi.mock("../../../integrations/misc/extract-text", () => ({
everyLineHasLineNumbers: vi.fn().mockReturnValue(false),
stripLineNumbers: vi.fn().mockImplementation((content) => content),
addLineNumbers: vi.fn().mockImplementation((content: string) =>
content
.split("\n")
.map((line: string, i: number) => `${i + 1} | ${line}`)
.join("\n"),
),
}))
vi.mock("vscode", () => ({
window: {
showWarningMessage: vi.fn().mockResolvedValue(undefined),
},
env: {
openExternal: vi.fn(),
},
Uri: {
parse: vi.fn(),
},
}))
vi.mock("../../ignore/RooIgnoreController", () => ({
RooIgnoreController: class {
initialize() {
return Promise.resolve()
}
validateAccess() {
return true
}
},
}))
describe("writeToFileTool", () => {
// Test data
const testFilePath = "test/file.txt"
const absoluteFilePath = process.platform === "win32" ? "C:\\test\\file.txt" : "/test/file.txt"
const testContent = "Line 1\nLine 2\nLine 3"
const testContentWithMarkdown = "```javascript\nLine 1\nLine 2\n```"
// Mocked functions with correct types
const mockedFileExistsAtPath = fileExistsAtPath as MockedFunction<typeof fileExistsAtPath>
const mockedCreateDirectoriesForFile = createDirectoriesForFile as MockedFunction<typeof createDirectoriesForFile>
const mockedIsPathOutsideWorkspace = isPathOutsideWorkspace as MockedFunction<typeof isPathOutsideWorkspace>
const mockedGetReadablePath = getReadablePath as MockedFunction<typeof getReadablePath>
const mockedEveryLineHasLineNumbers = everyLineHasLineNumbers as MockedFunction<typeof everyLineHasLineNumbers>
const mockedStripLineNumbers = stripLineNumbers as MockedFunction<typeof stripLineNumbers>
const mockedPathResolve = path.resolve as MockedFunction<typeof path.resolve>
const mockCline: any = {}
let mockAskApproval: ReturnType<typeof vi.fn>
let mockHandleError: ReturnType<typeof vi.fn>
let mockPushToolResult: ReturnType<typeof vi.fn>
let mockRemoveClosingTag: ReturnType<typeof vi.fn>
let toolResult: ToolResponse | undefined
beforeEach(() => {
vi.clearAllMocks()
mockedPathResolve.mockReturnValue(absoluteFilePath)
mockedFileExistsAtPath.mockResolvedValue(false)
mockedIsPathOutsideWorkspace.mockReturnValue(false)
mockedGetReadablePath.mockReturnValue("test/path.txt")
mockedEveryLineHasLineNumbers.mockReturnValue(false)
mockedStripLineNumbers.mockImplementation((content) => content)
mockCline.cwd = "/"
mockCline.consecutiveMistakeCount = 0
mockCline.didEditFile = false
mockCline.diffStrategy = undefined
mockCline.providerRef = {
deref: vi.fn().mockReturnValue({
getState: vi.fn().mockResolvedValue({
diagnosticsEnabled: true,
writeDelayMs: 1000,
}),
}),
}
mockCline.rooIgnoreController = {
validateAccess: vi.fn().mockReturnValue(true),
}
mockCline.diffViewProvider = {
editType: undefined,
isEditing: false,
originalContent: "",
open: vi.fn().mockResolvedValue(undefined),
update: vi.fn().mockResolvedValue(undefined),
reset: vi.fn().mockResolvedValue(undefined),
revertChanges: vi.fn().mockResolvedValue(undefined),
saveChanges: vi.fn().mockResolvedValue({
newProblemsMessage: "",
userEdits: null,
finalContent: "final content",
}),
scrollToFirstDiff: vi.fn(),
updateDiagnosticSettings: vi.fn(),
pushToolWriteResult: vi.fn().mockImplementation(async function (
this: any,
task: any,
cwd: string,
isNewFile: boolean,
) {
// Simulate the behavior of pushToolWriteResult
if (this.userEdits) {
await task.say(
"user_feedback_diff",
JSON.stringify({
tool: isNewFile ? "newFileCreated" : "editedExistingFile",
path: "test/path.txt",
diff: this.userEdits,
}),
)
}
return "Tool result message"
}),
}
mockCline.api = {
getModel: vi.fn().mockReturnValue({ id: "claude-3" }),
}
mockCline.fileContextTracker = {
trackFileContext: vi.fn().mockResolvedValue(undefined),
}
mockCline.say = vi.fn().mockResolvedValue(undefined)
mockCline.ask = vi.fn().mockResolvedValue(undefined)
mockCline.recordToolError = vi.fn()
mockCline.sayAndCreateMissingParamError = vi.fn().mockResolvedValue("Missing param error")
mockAskApproval = vi.fn().mockResolvedValue(true)
mockHandleError = vi.fn().mockResolvedValue(undefined)
mockRemoveClosingTag = vi.fn((tag, content) => content)
toolResult = undefined
})
/**
* Helper function to execute the write file tool with different parameters
*/
async function executeWriteFileTool(
params: Partial<ToolUse["params"]> = {},
options: {
fileExists?: boolean
isPartial?: boolean
accessAllowed?: boolean
} = {},
): Promise<ToolResponse | undefined> {
// Configure mocks based on test scenario
const fileExists = options.fileExists ?? false
const isPartial = options.isPartial ?? false
const accessAllowed = options.accessAllowed ?? true
mockedFileExistsAtPath.mockResolvedValue(fileExists)
mockCline.rooIgnoreController.validateAccess.mockReturnValue(accessAllowed)
// Create a tool use object
const toolUse: ToolUse = {
type: "tool_use",
name: "write_to_file",
params: {
path: testFilePath,
content: testContent,
...params,
},
partial: isPartial,
}
mockPushToolResult = vi.fn((result: ToolResponse) => {
toolResult = result
})
await writeToFileTool.handle(mockCline, toolUse as ToolUse<"write_to_file">, {
askApproval: mockAskApproval,
handleError: mockHandleError,
pushToolResult: mockPushToolResult,
removeClosingTag: mockRemoveClosingTag,
toolProtocol: "xml",
})
return toolResult
}
describe("access control", () => {
it("validates and allows access when rooIgnoreController permits", async () => {
await executeWriteFileTool({}, { accessAllowed: true })
expect(mockCline.rooIgnoreController.validateAccess).toHaveBeenCalledWith(testFilePath)
expect(mockCline.diffViewProvider.open).toHaveBeenCalledWith(testFilePath)
})
})
describe("file existence detection", () => {
it.skipIf(process.platform === "win32")("detects existing file and sets editType to modify", async () => {
await executeWriteFileTool({}, { fileExists: true })
expect(mockedFileExistsAtPath).toHaveBeenCalledWith(absoluteFilePath)
expect(mockCline.diffViewProvider.editType).toBe("modify")
})
it.skipIf(process.platform === "win32")("detects new file and sets editType to create", async () => {
await executeWriteFileTool({}, { fileExists: false })
expect(mockedFileExistsAtPath).toHaveBeenCalledWith(absoluteFilePath)
expect(mockCline.diffViewProvider.editType).toBe("create")
})
it("uses cached editType without filesystem check", async () => {
mockCline.diffViewProvider.editType = "modify"
await executeWriteFileTool({})
expect(mockedFileExistsAtPath).not.toHaveBeenCalled()
})
})
describe("directory creation for new files", () => {
it.skipIf(process.platform === "win32")(
"creates parent directories early when file does not exist (execute)",
async () => {
await executeWriteFileTool({}, { fileExists: false })
expect(mockedCreateDirectoriesForFile).toHaveBeenCalledWith(absoluteFilePath)
},
)
it.skipIf(process.platform === "win32")(
"creates parent directories early when file does not exist (partial)",
async () => {
await executeWriteFileTool({}, { fileExists: false, isPartial: true })
expect(mockedCreateDirectoriesForFile).toHaveBeenCalledWith(absoluteFilePath)
},
)
it("does not create directories when file exists", async () => {
await executeWriteFileTool({}, { fileExists: true })
expect(mockedCreateDirectoriesForFile).not.toHaveBeenCalled()
})
it("does not create directories when editType is cached as modify", async () => {
mockCline.diffViewProvider.editType = "modify"
await executeWriteFileTool({})
expect(mockedCreateDirectoriesForFile).not.toHaveBeenCalled()
})
it.skipIf(process.platform === "win32")("creates directories when editType is cached as create", async () => {
mockCline.diffViewProvider.editType = "create"
await executeWriteFileTool({})
expect(mockedCreateDirectoriesForFile).toHaveBeenCalledWith(absoluteFilePath)
})
})
describe("content preprocessing", () => {
it("removes markdown code block markers from content", async () => {
await executeWriteFileTool({ content: testContentWithMarkdown })
expect(mockCline.diffViewProvider.update).toHaveBeenCalledWith("Line 1\nLine 2", true)
})
it("passes through empty content unchanged", async () => {
await executeWriteFileTool({ content: "" })
expect(mockCline.diffViewProvider.update).toHaveBeenCalledWith("", true)
})
it("strips line numbers from numbered content", async () => {
const contentWithLineNumbers = "1 | line one\n2 | line two"
mockedEveryLineHasLineNumbers.mockReturnValue(true)
mockedStripLineNumbers.mockReturnValue("line one\nline two")
await executeWriteFileTool({ content: contentWithLineNumbers })
expect(mockedEveryLineHasLineNumbers).toHaveBeenCalledWith(contentWithLineNumbers)
expect(mockedStripLineNumbers).toHaveBeenCalledWith(contentWithLineNumbers)
expect(mockCline.diffViewProvider.update).toHaveBeenCalledWith("line one\nline two", true)
})
})
describe("file operations", () => {
it("successfully creates new files with full workflow", async () => {
await executeWriteFileTool({}, { fileExists: false })
expect(mockCline.consecutiveMistakeCount).toBe(0)
expect(mockCline.diffViewProvider.open).toHaveBeenCalledWith(testFilePath)
expect(mockCline.diffViewProvider.update).toHaveBeenCalledWith(testContent, true)
expect(mockAskApproval).toHaveBeenCalled()
expect(mockCline.diffViewProvider.saveChanges).toHaveBeenCalled()
expect(mockCline.fileContextTracker.trackFileContext).toHaveBeenCalledWith(testFilePath, "roo_edited")
expect(mockCline.didEditFile).toBe(true)
})
it("processes files outside workspace boundary", async () => {
mockedIsPathOutsideWorkspace.mockReturnValue(true)
await executeWriteFileTool({})
expect(mockedIsPathOutsideWorkspace).toHaveBeenCalled()
})
it("processes files with large content", async () => {
const largeContent = "Line\n".repeat(10000)
await executeWriteFileTool({ content: largeContent })
// Should process normally without issues
expect(mockCline.consecutiveMistakeCount).toBe(0)
})
})
describe("partial block handling", () => {
it("returns early when path is missing in partial block", async () => {
await executeWriteFileTool({ path: undefined }, { isPartial: true })
expect(mockCline.diffViewProvider.open).not.toHaveBeenCalled()
})
it("returns early when content is undefined in partial block", async () => {
await executeWriteFileTool({ content: undefined }, { isPartial: true })
expect(mockCline.diffViewProvider.open).not.toHaveBeenCalled()
})
it("streams content updates during partial execution", async () => {
await executeWriteFileTool({}, { isPartial: true })
expect(mockCline.ask).toHaveBeenCalled()
expect(mockCline.diffViewProvider.open).toHaveBeenCalledWith(testFilePath)
expect(mockCline.diffViewProvider.update).toHaveBeenCalledWith(testContent, false)
})
})
describe("user interaction", () => {
it("reverts changes when user rejects approval", async () => {
mockAskApproval.mockResolvedValue(false)
await executeWriteFileTool({})
expect(mockCline.diffViewProvider.revertChanges).toHaveBeenCalled()
expect(mockCline.diffViewProvider.saveChanges).not.toHaveBeenCalled()
})
it("reports user edits with diff feedback", async () => {
const userEditsValue = "- old line\n+ new line"
mockCline.diffViewProvider.saveChanges.mockResolvedValue({
newProblemsMessage: " with warnings",
userEdits: userEditsValue,
finalContent: "modified content",
})
// Set the userEdits property on the diffViewProvider mock to simulate user edits
mockCline.diffViewProvider.userEdits = userEditsValue
await executeWriteFileTool({}, { fileExists: true })
expect(mockCline.say).toHaveBeenCalledWith(
"user_feedback_diff",
expect.stringContaining("editedExistingFile"),
)
})
})
describe("error handling", () => {
it("handles general file operation errors", async () => {
mockCline.diffViewProvider.open.mockRejectedValue(new Error("General error"))
await executeWriteFileTool({})
expect(mockHandleError).toHaveBeenCalledWith("writing file", expect.any(Error))
expect(mockCline.diffViewProvider.reset).toHaveBeenCalled()
})
it("handles partial streaming errors", async () => {
mockCline.diffViewProvider.open.mockRejectedValue(new Error("Open failed"))
await executeWriteFileTool({}, { isPartial: true })
expect(mockHandleError).toHaveBeenCalledWith("handling partial write_to_file", expect.any(Error))
})
})
})