fix: treat files with only whitespace as empty in read_file tool

- Added trim() check to detect files containing only whitespace characters
- Files with only spaces, tabs, or newlines now show "File is empty" notice
- Original file content is preserved without modification
- Added test case to verify whitespace-only files are treated as empty

Fixes #5789
This commit is contained in:
Roo Code 2025-07-19 13:34:58 +00:00
parent e28fad131a
commit 63a5f669db
2 changed files with 21 additions and 2 deletions

View file

@ -481,6 +481,21 @@ describe("read_file tool XML output structure", () => {
`<files>\n<file><path>${testFilePath}</path>\n<content/><notice>File is empty</notice>\n</file>\n</files>`,
)
})
it("should treat files with only whitespace as empty", async () => {
// Setup - file has lines but only whitespace content
mockedCountFileLines.mockResolvedValue(3) // File has 3 lines
mockedExtractTextFromFile.mockResolvedValue(" \n\t\n ") // Only whitespace
mockProvider.getState.mockResolvedValue({ maxReadFileLine: -1 })
// Execute
const result = await executeReadFileTool({}, { totalLines: 3 })
// Verify - should show empty file notice even though totalLines > 0
expect(result).toBe(
`<files>\n<file><path>${testFilePath}</path>\n<content/><notice>File is empty</notice>\n</file>\n</files>`,
)
})
})
describe("Error Handling Tests", () => {

View file

@ -519,9 +519,13 @@ export async function readFileTool(
// Handle normal file read
const content = await extractTextFromFile(fullPath)
const lineRangeAttr = ` lines="1-${totalLines}"`
let xmlInfo = totalLines > 0 ? `<content${lineRangeAttr}>\n${content}</content>\n` : `<content/>`
if (totalLines === 0) {
// Check if file is effectively empty (no content or only whitespace)
const isEffectivelyEmpty = totalLines === 0 || content.trim() === ""
let xmlInfo = !isEffectivelyEmpty ? `<content${lineRangeAttr}>\n${content}</content>\n` : `<content/>`
if (isEffectivelyEmpty) {
xmlInfo += `<notice>File is empty</notice>\n`
}