From 97474139242f7a2e54576d19df8b3326717b3e16 Mon Sep 17 00:00:00 2001 From: Roo Code Date: Wed, 26 Nov 2025 23:54:11 +0000 Subject: [PATCH] fix: ensure parent directories exist before file operations in WriteToFileTool Fixes ENOENT errors when creating files in non-existent subdirectories by: - Wrapping fileExistsAtPath calls in try-catch blocks - Creating parent directories recursively when they do not exist - Treating files as new when parent directories need to be created This applies the fix from issue #9635 to the source code rather than the minified distribution file. --- src/core/tools/WriteToFileTool.ts | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/src/core/tools/WriteToFileTool.ts b/src/core/tools/WriteToFileTool.ts index 475be66c2c..03e5cc47cf 100644 --- a/src/core/tools/WriteToFileTool.ts +++ b/src/core/tools/WriteToFileTool.ts @@ -75,7 +75,20 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> { fileExists = task.diffViewProvider.editType === "modify" } else { const absolutePath = path.resolve(task.cwd, relPath) - fileExists = await fileExistsAtPath(absolutePath) + // Ensure parent directory exists before checking file existence + try { + fileExists = await fileExistsAtPath(absolutePath) + } catch (error) { + // If we get ENOENT, the parent directory might not exist + // Create the parent directory and treat this as a new file + const parentDir = path.dirname(absolutePath) + try { + await fs.mkdir(parentDir, { recursive: true }) + } catch { + // Ignore errors from mkdir, we'll handle them when writing + } + fileExists = false + } task.diffViewProvider.editType = fileExists ? "modify" : "create" } @@ -311,7 +324,20 @@ export class WriteToFileTool extends BaseTool<"write_to_file"> { fileExists = task.diffViewProvider.editType === "modify" } else { const absolutePath = path.resolve(task.cwd, relPath) - fileExists = await fileExistsAtPath(absolutePath) + // Ensure parent directory exists before checking file existence + try { + fileExists = await fileExistsAtPath(absolutePath) + } catch (error) { + // If we get ENOENT, the parent directory might not exist + // Create the parent directory and treat this as a new file + const parentDir = path.dirname(absolutePath) + try { + await fs.mkdir(parentDir, { recursive: true }) + } catch { + // Ignore errors from mkdir, we'll handle them when writing + } + fileExists = false + } task.diffViewProvider.editType = fileExists ? "modify" : "create" }