/** * Tests for ReadFileTool - Codex-inspired file reading with indentation mode support. * * These tests cover: * - Input validation (missing path parameter) * - RooIgnore blocking * - Directory read error handling * - Binary file handling (images, PDF, DOCX, unsupported) * - Image memory limits * - Approval flow (approve, deny, feedback) * - Text file processing (slice and indentation modes) * - Output structure formatting */ import os from "os" import path from "path" import type { Stats } from "fs" import type { LegacyReadFileParams } from "@roo-code/types" import type { ToolUse } from "../../../shared/tools" import type { Task, ToolExecutionContext } from "../../task/Task" import { isBinaryFile } from "isbinaryfile" import { readFileTool } from "../ReadFileTool" import { ObservationRegistry } from "../../task/observationRegistry" import { formatResponse } from "../../prompts/responses" import { validateImageForProcessing, processImageFile, isSupportedImageFormat } from "../helpers/imageHelpers" import { extractTextFromFile, getSupportedBinaryFormats } from "../../../integrations/misc/extract-text" import { readWithIndentation, readWithSlice } from "../../../integrations/misc/indentation-reader" // ─── Mocks ──────────────────────────────────────────────────────────────────── vi.mock("path", async () => { const originalPath = await vi.importActual("path") return { default: originalPath, ...originalPath, resolve: vi.fn().mockImplementation((...args) => { return args.join("/") }), } }) vi.mock("fs/promises", () => ({ readFile: vi.fn(), stat: vi.fn(), })) vi.mock("isbinaryfile") vi.mock("../../../integrations/misc/extract-text", () => ({ extractTextFromFile: vi.fn(), addLineNumbers: vi.fn().mockImplementation((text: string, startLine = 1) => { if (!text) return "" const lines = text.split("\n") return lines.map((line, i) => `${startLine + i} | ${line}`).join("\n") }), getSupportedBinaryFormats: vi.fn(() => [".pdf", ".docx", ".ipynb"]), })) vi.mock("../../../integrations/misc/indentation-reader", () => ({ readWithIndentation: vi.fn(), readWithSlice: vi.fn(), })) vi.mock("../helpers/imageHelpers", () => ({ DEFAULT_MAX_IMAGE_FILE_SIZE_MB: 5, DEFAULT_MAX_TOTAL_IMAGE_SIZE_MB: 20, isSupportedImageFormat: vi.fn(), validateImageForProcessing: vi.fn(), processImageFile: vi.fn(), ImageMemoryTracker: vi.fn().mockImplementation(function () { return { getTotalMemoryUsed: vi.fn().mockReturnValue(0), addMemoryUsage: vi.fn(), } }), })) vi.mock("../../prompts/responses", () => ({ formatResponse: { toolDenied: vi.fn(() => "The user denied this operation."), toolDeniedWithFeedback: vi.fn( (feedback?: string) => `The user denied this operation and responded with the message:\n\n${feedback}\n`, ), toolApprovedWithFeedback: vi.fn( (feedback?: string) => `The user approved this operation and responded with the message:\n\n${feedback}\n`, ), rooIgnoreError: vi.fn( (filePath: string) => `Access to ${filePath} is blocked by the .rooignore file settings. You must try to continue in the task without using this file, or ask the user to update the .rooignore file.`, ), toolResult: vi.fn((text: string, images?: string[]) => { if (images && images.length > 0) { return [ { type: "text", text }, ...images.map((img) => { const [header, data] = img.split(",") const media_type = header.match(/:(.*?);/)?.[1] || "image/png" return { type: "image", source: { type: "base64", media_type, data } } }), ] } return text }), imageBlocks: vi.fn((images?: string[]) => { return images ? images.map((img) => { const [header, data] = img.split(",") const media_type = header.match(/:(.*?);/)?.[1] || "image/png" return { type: "image", source: { type: "base64", media_type, data } } }) : [] }), }, })) // Mock fs/promises const fsPromises = await import("fs/promises") const mockedFsReadFile = vi.mocked(fsPromises.readFile) const mockedFsStat = vi.mocked(fsPromises.stat) const mockedIsBinaryFile = vi.mocked(isBinaryFile) const mockedExtractTextFromFile = vi.mocked(extractTextFromFile) const mockedReadWithSlice = vi.mocked(readWithSlice) const mockedReadWithIndentation = vi.mocked(readWithIndentation) const mockedIsSupportedImageFormat = vi.mocked(isSupportedImageFormat) const mockedValidateImageForProcessing = vi.mocked(validateImageForProcessing) const mockedProcessImageFile = vi.mocked(processImageFile) // ─── Test Helpers ───────────────────────────────────────────────────────────── interface MockTaskOptions { supportsImages?: boolean rooIgnoreAllowed?: boolean maxImageFileSize?: number maxTotalImageSize?: number observationRegistry?: ObservationRegistry } function createMockTask(options: MockTaskOptions = {}) { const { supportsImages = false, rooIgnoreAllowed = true, maxImageFileSize = 5, maxTotalImageSize = 20 } = options return { cwd: "/test/workspace", // Mirror Task: every task always owns an observation registry (A2, #1375). // Tests asserting on observations pass their own instance via options. observationRegistry: options.observationRegistry ?? new ObservationRegistry(), api: { getModel: vi.fn().mockReturnValue({ info: { supportsImages }, }), }, consecutiveMistakeCount: 0, didToolFailInCurrentTurn: false, didRejectTool: false, activeToolContexts: new Map(), ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }), say: vi.fn().mockResolvedValue(undefined), sayAndCreateMissingParamError: vi.fn().mockResolvedValue("Missing required parameter: path"), recordToolError: vi.fn(), rooIgnoreController: { validateAccess: vi.fn().mockReturnValue(rooIgnoreAllowed), }, fileContextTracker: { trackFileContext: vi.fn().mockResolvedValue(undefined), }, providerRef: { deref: vi.fn().mockReturnValue({ getState: vi.fn().mockResolvedValue({ maxImageFileSize, maxTotalImageSize, }), }), }, } } function createMockCallbacks() { return { pushToolResult: vi.fn(), toolCallId: "test-tool-call-id", askApproval: vi.fn(), handleError: vi.fn(), } } // ─── Tests ──────────────────────────────────────────────────────────────────── describe("ReadFileTool", () => { beforeEach(() => { vi.clearAllMocks() // Default mock implementations // The stat default carries BigIntStats fields (A2, epic #1375): reads now // token-ize the pre/post stats, so the default must look like a real bigint stat. // Tests overriding it do so per-call with mockResolvedValue(Once). mockedFsStat.mockResolvedValue({ isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), // Cast: the mock only implements the members the tool and versionToken read. } as unknown as Stats) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("test content")) mockedReadWithSlice.mockReturnValue({ content: "1 | test content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) }) describe("input validation", () => { it("should return error when path is missing", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() await readFileTool.execute({ path: "" } as any, mockTask as any, callbacks) expect(mockTask.consecutiveMistakeCount).toBe(1) expect(mockTask.recordToolError).toHaveBeenCalledWith("read_file") expect(mockTask.sayAndCreateMissingParamError).toHaveBeenCalledWith("read_file", "path") expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Error:")) }) it("should return error when path is undefined", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() await readFileTool.execute({} as any, mockTask as any, callbacks) expect(mockTask.consecutiveMistakeCount).toBe(1) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Error:")) }) it("should return error when offset is 0 or negative", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() await readFileTool.execute({ path: "test.txt", offset: 0 }, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("offset must be a 1-indexed line number"), ) }) it("should return error when offset is negative", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() await readFileTool.execute({ path: "test.txt", offset: -5 }, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("offset must be a 1-indexed line number"), ) }) it("should return error when anchor_line is 0 or negative", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() await readFileTool.execute( { path: "test.txt", mode: "indentation", indentation: { anchor_line: 0 }, }, mockTask as any, callbacks, ) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("anchor_line must be a 1-indexed line number"), ) }) it("should return error when anchor_line is negative", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() await readFileTool.execute( { path: "test.txt", mode: "indentation", indentation: { anchor_line: -10 }, }, mockTask as any, callbacks, ) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("anchor_line must be a 1-indexed line number"), ) }) }) describe("RooIgnore handling", () => { it("should block access to rooignore-protected files", async () => { const mockTask = createMockTask({ rooIgnoreAllowed: false }) const callbacks = createMockCallbacks() await readFileTool.execute({ path: "secret.env" }, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("rooignore_error", "secret.env") expect(formatResponse.rooIgnoreError).toHaveBeenCalledWith("secret.env") expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("blocked by the .rooignore")) }) }) describe("directory handling", () => { it("should return error when trying to read a directory", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue({ isDirectory: () => true } as any) await readFileTool.execute({ path: "src/utils" }, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith( "error", expect.stringContaining("Cannot read 'src/utils' because it is a directory"), ) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("it is a directory")) expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) }) describe("image handling", () => { beforeEach(() => { mockedIsBinaryFile.mockResolvedValue(true) mockedIsSupportedImageFormat.mockReturnValue(true) }) it("should process image file when model supports images", async () => { const mockTask = createMockTask({ supportsImages: true }) const callbacks = createMockCallbacks() mockedValidateImageForProcessing.mockResolvedValue({ isValid: true, sizeInMB: 0.5, }) mockedProcessImageFile.mockResolvedValue({ dataUrl: "data:image/png;base64,abc123", buffer: Buffer.from("test"), sizeInKB: 512, sizeInMB: 0.5, notice: "Image processed successfully", }) await readFileTool.execute({ path: "image.png" }, mockTask as any, callbacks) expect(mockedValidateImageForProcessing).toHaveBeenCalled() expect(mockedProcessImageFile).toHaveBeenCalled() expect(callbacks.pushToolResult).toHaveBeenCalled() }) it("should skip image when model does not support images", async () => { const mockTask = createMockTask({ supportsImages: false }) const callbacks = createMockCallbacks() mockedValidateImageForProcessing.mockResolvedValue({ isValid: false, reason: "unsupported_model", notice: "Model does not support image processing", }) await readFileTool.execute({ path: "image.png" }, mockTask as any, callbacks) expect(mockedValidateImageForProcessing).toHaveBeenCalled() expect(mockedProcessImageFile).not.toHaveBeenCalled() expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("Model does not support image processing"), ) }) it("should skip image when file exceeds size limit", async () => { const mockTask = createMockTask({ supportsImages: true, maxImageFileSize: 1 }) const callbacks = createMockCallbacks() mockedValidateImageForProcessing.mockResolvedValue({ isValid: false, reason: "size_limit", notice: "Image file size (10 MB) exceeds the maximum allowed size (1 MB)", }) await readFileTool.execute({ path: "large-image.png" }, mockTask as any, callbacks) expect(mockedProcessImageFile).not.toHaveBeenCalled() expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("exceeds the maximum allowed"), ) }) it("should skip image when total memory limit exceeded", async () => { const mockTask = createMockTask({ supportsImages: true, maxTotalImageSize: 5 }) const callbacks = createMockCallbacks() mockedValidateImageForProcessing.mockResolvedValue({ isValid: false, reason: "memory_limit", notice: "Skipping image: would exceed total memory limit", }) await readFileTool.execute({ path: "another-image.png" }, mockTask as any, callbacks) expect(mockedProcessImageFile).not.toHaveBeenCalled() expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("would exceed total memory")) }) it("should handle image read errors gracefully", async () => { const mockTask = createMockTask({ supportsImages: true }) const callbacks = createMockCallbacks() mockedValidateImageForProcessing.mockResolvedValue({ isValid: true, sizeInMB: 0.5, }) mockedProcessImageFile.mockRejectedValue(new Error("Failed to read image")) await readFileTool.execute({ path: "corrupt.png" }, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("Error reading image file")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Error")) }) }) describe("binary file handling", () => { beforeEach(() => { mockedIsBinaryFile.mockResolvedValue(true) mockedIsSupportedImageFormat.mockReturnValue(false) }) it("should extract text from PDF files", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedExtractTextFromFile.mockResolvedValue("PDF content here") await readFileTool.execute({ path: "document.pdf" }, mockTask as any, callbacks) expect(mockedExtractTextFromFile).toHaveBeenCalled() expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("PDF content here")) }) it("should extract text from DOCX files", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedExtractTextFromFile.mockResolvedValue("DOCX content here") await readFileTool.execute({ path: "document.docx" }, mockTask as any, callbacks) expect(mockedExtractTextFromFile).toHaveBeenCalled() expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("DOCX content here")) }) it("should handle unsupported binary formats", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() // Return empty array to indicate .exe is not supported vi.mocked(getSupportedBinaryFormats).mockReturnValue([".pdf", ".docx"]) await readFileTool.execute({ path: "program.exe" }, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Binary file")) }) it("should handle extraction errors gracefully", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedExtractTextFromFile.mockRejectedValue(new Error("Extraction failed")) await readFileTool.execute({ path: "corrupt.pdf" }, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("Error extracting text")) expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) }) describe("text file processing", () => { beforeEach(() => { mockedIsBinaryFile.mockResolvedValue(false) }) it("should read text file with slice mode (default)", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() const content = "line 1\nline 2\nline 3" mockedFsReadFile.mockResolvedValue(Buffer.from(content)) mockedReadWithSlice.mockReturnValue({ content: "1 | line 1\n2 | line 2\n3 | line 3", returnedLines: 3, totalLines: 3, wasTruncated: false, includedRanges: [[1, 3]], }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) expect(mockedReadWithSlice).toHaveBeenCalled() expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("line 1")) }) it("should read text file with offset and limit", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\nline 2\nline 3\nline 4\nline 5")) mockedReadWithSlice.mockReturnValue({ content: "2 | line 2\n3 | line 3", returnedLines: 2, totalLines: 5, wasTruncated: true, includedRanges: [[2, 3]], }) await readFileTool.execute( { path: "test.ts", mode: "slice", offset: 2, limit: 2 }, mockTask as any, callbacks, ) expect(mockedReadWithSlice).toHaveBeenCalledWith(expect.any(String), 1, 2) // offset converted to 0-based }) it("should read text file with indentation mode", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() const content = "class Foo {\n method() {\n return 42\n }\n}" mockedFsReadFile.mockResolvedValue(Buffer.from(content)) mockedReadWithIndentation.mockReturnValue({ content: "1 | class Foo {\n2 | method() {\n3 | return 42\n4 | }\n5 | }", returnedLines: 5, totalLines: 5, wasTruncated: false, includedRanges: [[1, 5]], }) await readFileTool.execute( { path: "test.ts", mode: "indentation", indentation: { anchor_line: 3 }, }, mockTask as any, callbacks, ) expect(mockedReadWithIndentation).toHaveBeenCalledWith( content, expect.objectContaining({ anchorLine: 3, }), ) }) it("should show truncation notice when content is truncated", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("lots of content...")) mockedReadWithSlice.mockReturnValue({ content: "1 | truncated content", returnedLines: 100, totalLines: 5000, wasTruncated: true, includedRanges: [[1, 100]], }) await readFileTool.execute({ path: "large.ts" }, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("truncated")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("To read more")) }) it("should handle empty files", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("")) mockedReadWithSlice.mockReturnValue({ content: "", returnedLines: 0, totalLines: 0, wasTruncated: false, includedRanges: [], }) await readFileTool.execute({ path: "empty.ts" }, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Note: File is empty")) }) it("should propagate beyond-EOF error instead of reporting file as empty", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("line1\nline2\nline3\nline4\nline5")) mockedReadWithSlice.mockReturnValue({ content: "Error: offset 100 is beyond file end (5 lines)", returnedLines: 0, totalLines: 5, wasTruncated: false, includedRanges: [], }) await readFileTool.execute( { path: "test.ts", mode: "slice", offset: 100 }, mockTask as unknown as Task, callbacks, ) expect(mockedReadWithSlice).toHaveBeenCalledWith(expect.any(String), 99, expect.any(Number)) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("beyond file end")) expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Note: File is empty")) }) // Integration counterpart to the mocked case above: the real readWithSlice // producer runs against a real file, so the error text and its 1-based // offset are proven end-to-end instead of being asserted against a stub. it("should propagate the real beyond-EOF error from the producer for a real file", async () => { const realFs = await vi.importActual("fs/promises") const realPath = await vi.importActual("path") const tempDir = await realFs.mkdtemp(realPath.join(os.tmpdir(), "read-file-beyond-eof-")) const fileName = "sample.txt" await realFs.writeFile(realPath.join(tempDir, fileName), "line1\nline2\nline3\nline4\nline5", "utf8") vi.doUnmock("fs/promises") vi.doUnmock("path") vi.doUnmock("isbinaryfile") vi.doUnmock("../../../integrations/misc/indentation-reader") vi.resetModules() try { const { ReadFileTool } = await import("../ReadFileTool") const mockTask = { ...createMockTask(), cwd: tempDir } const callbacks = createMockCallbacks() await new ReadFileTool().execute( { path: fileName, mode: "slice", offset: 100 }, mockTask as unknown as Task, callbacks, ) expect(mockedReadWithSlice).not.toHaveBeenCalled() expect(callbacks.pushToolResult).toHaveBeenCalledTimes(1) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("Error: offset 100 is beyond file end (5 lines)"), ) expect(callbacks.pushToolResult).not.toHaveBeenCalledWith( expect.stringContaining("Note: File is empty"), ) } finally { vi.resetModules() await realFs.rm(tempDir, { recursive: true, force: true }).catch(() => {}) } }) }) describe("approval flow", () => { it("should approve file read when user clicks yes", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) expect(mockTask.ask).toHaveBeenCalledWith("tool", expect.any(String), false) expect(mockTask.didRejectTool).toBe(false) }) it("should deny file read when user clicks no", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() const context = { toolCallId: callbacks.toolCallId, didReject: false } mockTask.activeToolContexts.set(callbacks.toolCallId, context) mockTask.ask.mockResolvedValue({ response: "noButtonClicked", text: undefined, images: undefined }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) expect(mockTask.didRejectTool).toBe(true) expect(context.didReject).toBe(true) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Denied by user")) }) it("should include user feedback when provided with approval", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: "Please be careful with this file", images: undefined, }) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "1 | content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("user_feedback", "Please be careful with this file", undefined) expect(formatResponse.toolApprovedWithFeedback).toHaveBeenCalledWith("Please be careful with this file") }) it("should include user feedback when provided with denial", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "noButtonClicked", text: "This file contains secrets", images: undefined, }) await readFileTool.execute({ path: "secrets.env" }, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("user_feedback", "This file contains secrets", undefined) expect(formatResponse.toolDeniedWithFeedback).toHaveBeenCalledWith("This file contains secrets") }) }) describe("output structure", () => { it("should include file path in output", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "1 | content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "src/app.ts" }, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("File: src/app.ts")) }) it("should track file context after successful read", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "1 | content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) expect(mockTask.fileContextTracker.trackFileContext).toHaveBeenCalledWith("test.ts", "read_tool") }) }) describe("error handling", () => { it("should handle file read errors gracefully", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockRejectedValue(new Error("ENOENT: no such file or directory")) await readFileTool.execute({ path: "nonexistent.ts" }, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("Error reading file")) expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) it("should handle stat errors gracefully", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsStat.mockRejectedValue(new Error("Permission denied")) await readFileTool.execute({ path: "protected.ts" }, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("Error reading file")) expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) }) describe("getReadFileToolDescription", () => { it("should return description with path when nativeArgs provided", () => { const description = readFileTool.getReadFileToolDescription("read_file", { path: "src/app.ts" }) expect(description).toBe("[read_file for 'src/app.ts']") }) it("should return description with path when params provided", () => { const description = readFileTool.getReadFileToolDescription("read_file", { path: "src/app.ts" }) expect(description).toBe("[read_file for 'src/app.ts']") }) it("should return description indicating missing path", () => { const description = readFileTool.getReadFileToolDescription("read_file", {}) expect(description).toBe("[read_file with missing path]") }) }) describe("legacy format handling", () => { it("should detect legacy format and use backward compatibility path", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedFsReadFile.mockResolvedValue(Buffer.from("legacy content")) await readFileTool.execute({ files: [{ path: "legacy.ts" }] } as any, mockTask as any, callbacks) // The legacy path emits "File: " entries — proof the backward-compat branch ran. expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("File: legacy.ts")) }) it("should return error when legacy files array is empty", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() await readFileTool.execute({ files: [] } as any, mockTask as any, callbacks) expect(mockTask.consecutiveMistakeCount).toBe(1) expect(mockTask.recordToolError).toHaveBeenCalledWith("read_file") expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Error:")) }) it("should handle multiple files in legacy format", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedFsReadFile.mockResolvedValueOnce(Buffer.from("file1 content")) mockedFsReadFile.mockResolvedValueOnce(Buffer.from("file2 content")) // Override readWithSlice to return content that reflects the actual file data mockedReadWithSlice .mockReturnValueOnce({ content: "1 | file1 content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) .mockReturnValueOnce({ content: "1 | file2 content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute( { files: [{ path: "file1.ts" }, { path: "file2.ts" }] } as any, mockTask as any, callbacks, ) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("file1 content")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("file2 content")) }) describe("batch approval denial", () => { const requestBatchApproval = async (answer: { response: string text?: string approvedIndexes?: number[] }) => { const mockTask = createMockTask() const context = { toolCallId: "batch-call", didReject: false } mockTask.activeToolContexts.set("batch-call", context) mockTask.ask.mockImplementation(async (_type: string, message: string) => { if (!answer.approvedIndexes) return { response: answer.response, text: answer.text } const { batchFiles } = JSON.parse(message) as { batchFiles: { key: string }[] } const permissions = Object.fromEntries( batchFiles.map((file, index) => [file.key, answer.approvedIndexes!.includes(index)]), ) return { response: answer.response, text: JSON.stringify(permissions) } }) const updateFileResult = vi.fn() const filesToApprove = ["file1.ts", "file2.ts"].map((path) => ({ path, status: "pending" as const, entry: { path }, })) await readFileTool["requestApproval"](mockTask as never, "batch-call", filesToApprove, updateFileResult) return { mockTask, context, updateFileResult } } it.each([ ["the user clicks no", { response: "noButtonClicked" }], ["individual permissions deny every file", { response: "messageResponse", text: "{}" }], ["individual permissions are not valid JSON", { response: "messageResponse", text: "not json" }], ])("marks the tool call rejected and denies both files when %s", async (_name, askResult) => { const { mockTask, context, updateFileResult } = await requestBatchApproval(askResult) expect(mockTask.didRejectTool).toBe(true) expect(context.didReject).toBe(true) expect(updateFileResult).toHaveBeenCalledWith("file1.ts", expect.objectContaining({ status: "denied" })) expect(updateFileResult).toHaveBeenCalledWith("file2.ts", expect.objectContaining({ status: "denied" })) }) it("marks the tool call rejected when individual permissions approve one file and deny the other", async () => { const { mockTask, context, updateFileResult } = await requestBatchApproval({ response: "messageResponse", approvedIndexes: [0], }) expect(mockTask.didRejectTool).toBe(true) expect(context.didReject).toBe(true) expect(updateFileResult).toHaveBeenCalledWith("file1.ts", { status: "approved" }) expect(updateFileResult).toHaveBeenCalledWith("file2.ts", expect.objectContaining({ status: "denied" })) }) it("leaves the tool call unrejected when individual permissions approve every file", async () => { const { mockTask, context, updateFileResult } = await requestBatchApproval({ response: "messageResponse", approvedIndexes: [0, 1], }) expect(mockTask.didRejectTool).toBe(false) expect(context.didReject).toBe(false) expect(updateFileResult).toHaveBeenCalledWith("file1.ts", { status: "approved" }) expect(updateFileResult).toHaveBeenCalledWith("file2.ts", { status: "approved" }) }) }) it("should block rooignore-protected files in legacy format", async () => { const mockTask = createMockTask({ rooIgnoreAllowed: false }) const callbacks = createMockCallbacks() await readFileTool.execute({ files: [{ path: "secret.env" }] } as any, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("rooignore_error", "secret.env") expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("blocked by the .rooignore")) // Consistent with the native path: a blocked file fails the tool turn. expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) it("should deny legacy file read when user clicks no", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "noButtonClicked", text: undefined, images: undefined }) await readFileTool.execute({ files: [{ path: "protected.ts" }] } as any, mockTask as any, callbacks) expect(mockTask.didRejectTool).toBe(true) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Denied by user")) }) it("should handle directory path in legacy format", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedFsStat.mockResolvedValue({ isDirectory: () => true } as any) await readFileTool.execute({ files: [{ path: "src/utils" }] } as any, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("it is a directory")) // Consistent with the native path: a failed read fails the tool turn. expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) it("should handle line ranges in legacy format", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) // fs.readFile with "utf8" encoding returns a string, not a Buffer mockedFsReadFile.mockResolvedValue(Buffer.from("line1\nline2\nline3\nline4\nline5")) await readFileTool.execute( { files: [{ path: "test.ts", lineRanges: [{ start: 2, end: 4 }] }] } as any, mockTask as any, callbacks, ) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("2 | line2")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("4 | line4")) }) it("should handle binary image files in legacy format with image support", async () => { const mockTask = createMockTask({ supportsImages: true }) const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedIsBinaryFile.mockResolvedValue(true) mockedIsSupportedImageFormat.mockReturnValue(true) mockedValidateImageForProcessing.mockResolvedValue({ isValid: true, sizeInMB: 0.5, }) mockedProcessImageFile.mockResolvedValue({ dataUrl: "data:image/png;base64,abc123", buffer: Buffer.from("test"), sizeInKB: 512, sizeInMB: 0.5, notice: "Image processed successfully", }) await readFileTool.execute({ files: [{ path: "image.png" }] } as any, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("Image file - content processed"), ) }) it("should handle binary image validation failure in legacy format", async () => { const mockTask = createMockTask({ supportsImages: true }) const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedIsBinaryFile.mockResolvedValue(true) mockedIsSupportedImageFormat.mockReturnValue(true) mockedValidateImageForProcessing.mockResolvedValue({ isValid: false, reason: "size_limit", notice: "Image too large", }) await readFileTool.execute({ files: [{ path: "large.png" }] } as any, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Image too large")) }) it("should handle unsupported binary files in legacy format", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedIsBinaryFile.mockResolvedValue(true) mockedIsSupportedImageFormat.mockReturnValue(false) await readFileTool.execute({ files: [{ path: "program.exe" }] } as any, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Cannot read binary file")) }) it("should handle file read errors in legacy format", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedFsReadFile.mockRejectedValue(new Error("ENOENT")) await readFileTool.execute({ files: [{ path: "missing.ts" }] } as any, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("Error reading file")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("ENOENT")) // Consistent with the native path: a failed read fails the tool turn. expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) it("should handle user feedback on approval in legacy format", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: "Read carefully", images: undefined, }) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) await readFileTool.execute({ files: [{ path: "test.ts" }] } as any, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("user_feedback", "Read carefully", undefined) }) it("should handle user feedback on denial in legacy format", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "noButtonClicked", text: "Not allowed", images: undefined, }) await readFileTool.execute({ files: [{ path: "secret.ts" }] } as any, mockTask as any, callbacks) expect(mockTask.say).toHaveBeenCalledWith("user_feedback", "Not allowed", undefined) }) it("should handle truncation in legacy format when no line ranges", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "1 | content", returnedLines: 100, totalLines: 5000, wasTruncated: true, includedRanges: [[1, 100]], }) await readFileTool.execute({ files: [{ path: "large.ts" }] } as any, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("File truncated")) }) it("should track file context in legacy format", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) await readFileTool.execute({ files: [{ path: "tracked.ts" }] } as any, mockTask as any, callbacks) expect(mockTask.fileContextTracker.trackFileContext).toHaveBeenCalledWith("tracked.ts", "read_tool") }) }) describe("handlePartial", () => { it.each([{}, { path: "" }, undefined])( "renders streamed native arguments before their path arrives: %j", async (nativeArgs) => { const mockTask = createMockTask() mockTask.cwd = path.resolve(mockTask.cwd) const streamedBlock = { type: "tool_use", name: "read_file", params: {}, nativeArgs, partial: true, } // Streaming JSON is incomplete even though finalized native arguments require a path. await Reflect.apply(readFileTool.handlePartial, readFileTool, [mockTask, streamedBlock]) expect(mockTask.ask).toHaveBeenCalledExactlyOnceWith( "tool", JSON.stringify({ tool: "readFile", path: "", isOutsideWorkspace: false }), true, ) expect(mockedFsReadFile).not.toHaveBeenCalled() expect(mockedFsStat).not.toHaveBeenCalled() expect(mockedExtractTextFromFile).not.toHaveBeenCalled() }, ) it("renders incomplete legacy arguments without a file entry or outside-workspace warning", async () => { const mockTask = createMockTask() mockTask.cwd = path.resolve(mockTask.cwd) const block: ToolUse<"read_file"> = { type: "tool_use", name: "read_file", params: {}, nativeArgs: { files: [], _legacyFormat: true }, partial: true, } // This reader-boundary double omits Task fields unrelated to file reading. await readFileTool.handlePartial(mockTask as unknown as Task, block) expect(mockTask.ask).toHaveBeenCalledExactlyOnceWith( "tool", JSON.stringify({ tool: "readFile", path: "", isOutsideWorkspace: false }), true, ) expect(mockedFsReadFile).not.toHaveBeenCalled() expect(mockedFsStat).not.toHaveBeenCalled() expect(mockedExtractTextFromFile).not.toHaveBeenCalled() }) it.each(["src/app.ts", "src/файл.ts", "src/e\u0301-📚.ts"])( "should preserve partial display for %s", async (filePath) => { const mockTask = createMockTask() mockTask.cwd = path.resolve(mockTask.cwd) mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) const block: ToolUse<"read_file"> = { type: "tool_use", name: "read_file", params: {}, nativeArgs: { path: filePath }, partial: true, } // This reader-boundary double omits Task fields unrelated to file reading. await readFileTool.handlePartial(mockTask as unknown as Task, block) expect(mockTask.ask).toHaveBeenCalledExactlyOnceWith( "tool", JSON.stringify({ tool: "readFile", path: filePath, isOutsideWorkspace: true }), true, ) }, ) it("should handle partial display for legacy format", async () => { const mockTask = createMockTask() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) const block = { nativeArgs: { files: [{ path: "legacy.ts" }] }, partial: false, } await readFileTool.handlePartial(mockTask as any, block as any) expect(mockTask.ask).toHaveBeenCalledWith("tool", expect.stringContaining("legacy.ts"), false) }) it("should handle partial display with empty path", async () => { const mockTask = createMockTask() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) const block = { nativeArgs: { path: "" }, partial: true, } await readFileTool.handlePartial(mockTask as any, block as any) expect(mockTask.ask).toHaveBeenCalled() }) it("should handle partial display with no nativeArgs", async () => { const mockTask = createMockTask() mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) const block = { nativeArgs: undefined, partial: true, } await readFileTool.handlePartial(mockTask as any, block as any) expect(mockTask.ask).toHaveBeenCalled() }) it.each(["Cancelled", "superseded"])("should gracefully handle %s ask rejection in partial", async (reason) => { const mockTask = createMockTask() mockTask.ask.mockRejectedValue(new Error(reason)) const block = { nativeArgs: { path: "test.ts" }, partial: true, } // Should not throw await readFileTool.handlePartial(mockTask as any, block as any) expect(mockTask.ask).toHaveBeenCalled() }) }) describe("processTextFile indentation mode edge cases", () => { beforeEach(() => { mockedIsBinaryFile.mockResolvedValue(false) }) it("should use offset as fallback when anchor_line is not provided in indentation mode", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithIndentation.mockReturnValue({ content: "5 | line 5 content", returnedLines: 1, totalLines: 10, wasTruncated: false, includedRanges: [[5, 5]], }) await readFileTool.execute( { path: "test.ts", mode: "indentation", offset: 5, } as any, mockTask as any, callbacks, ) expect(mockedReadWithIndentation).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ anchorLine: 5 }), ) }) it("should default anchorLine to 1 when neither anchor_line nor offset in indentation mode", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithIndentation.mockReturnValue({ content: "1 | first line", returnedLines: 1, totalLines: 10, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute( { path: "test.ts", mode: "indentation", } as any, mockTask as any, callbacks, ) expect(mockedReadWithIndentation).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ anchorLine: 1 }), ) }) it("should show truncation notice in indentation mode", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithIndentation.mockReturnValue({ content: "1 | truncated block", returnedLines: 50, totalLines: 200, wasTruncated: true, includedRanges: [[1, 50]], }) await readFileTool.execute( { path: "test.ts", mode: "indentation", indentation: { anchor_line: 1 }, }, mockTask as any, callbacks, ) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("File content truncated")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("To read more")) }) it("should include range information in indentation mode when not truncated", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithIndentation.mockReturnValue({ content: "5 | function foo() { ... }", returnedLines: 10, totalLines: 100, wasTruncated: false, includedRanges: [[5, 14]], }) await readFileTool.execute( { path: "test.ts", mode: "indentation", indentation: { anchor_line: 5 }, }, mockTask as any, callbacks, ) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Included ranges: 5-14")) }) it("should pass all indentation options to readWithIndentation", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithIndentation.mockReturnValue({ content: "result", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute( { path: "test.ts", mode: "indentation", indentation: { anchor_line: 10, max_levels: 2, include_siblings: true, include_header: false, max_lines: 200, }, limit: 500, }, mockTask as any, callbacks, ) expect(mockedReadWithIndentation).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ anchorLine: 10, maxLevels: 2, includeSiblings: true, includeHeader: false, limit: 500, maxLines: 200, }), ) }) }) describe("slice mode edge cases", () => { beforeEach(() => { mockedIsBinaryFile.mockResolvedValue(false) }) it("should convert 1-based offset to 0-based for readWithSlice", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("line1\nline2\nline3")) mockedReadWithSlice.mockReturnValue({ content: "4 | line4", returnedLines: 1, totalLines: 10, wasTruncated: false, includedRanges: [[4, 4]], }) await readFileTool.execute( { path: "test.ts", mode: "slice", offset: 4, limit: 1 }, mockTask as any, callbacks, ) // offset=4 (1-based) should become 3 (0-based) passed to readWithSlice expect(mockedReadWithSlice).toHaveBeenCalledWith(expect.any(String), 3, 1) }) it("should use default offset of 1 when not specified", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "1 | content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) // Default offset=1 -> 0-based = 0 expect(mockedReadWithSlice).toHaveBeenCalledWith(expect.any(String), 0, expect.any(Number)) }) it("should use default limit when not specified", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "1 | content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) // Should use DEFAULT_LINE_LIMIT (which is typically 2000) expect(mockedReadWithSlice).toHaveBeenCalledWith(expect.any(String), expect.any(Number), expect.any(Number)) }) it("should show correct line range in truncation notice", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("lots of content")) mockedReadWithSlice.mockReturnValue({ content: "5 | partial", returnedLines: 100, totalLines: 500, wasTruncated: true, includedRanges: [[5, 104]], }) await readFileTool.execute({ path: "test.ts", offset: 5, limit: 100 }, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Showing lines 5-104")) }) }) describe("getLineSnippet and getStartLine", () => { beforeEach(() => { mockedIsBinaryFile.mockResolvedValue(false) }) it("should show indentation mode snippet in approval message", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithIndentation.mockReturnValue({ content: "result", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute( { path: "test.ts", mode: "indentation", indentation: { anchor_line: 42 }, }, mockTask as any, callbacks, ) // The approval message should contain the indentation mode info const askCall = mockTask.ask.mock.calls[0] const message = JSON.parse(askCall[1]) expect(message.reason).toContain("indentation mode at line 42") }) it("should show line range in approval when offset > 1", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "result", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "test.ts", offset: 10, limit: 50 }, mockTask as any, callbacks) const askCall = mockTask.ask.mock.calls[0] const message = JSON.parse(askCall[1]) expect(message.reason).toContain("lines 10-59") expect(message.startLine).toBe(10) }) it("should show up to N lines in approval when offset is default", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "result", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) const askCall = mockTask.ask.mock.calls[0] const message = JSON.parse(askCall[1]) expect(message.reason).toContain("up to") expect(message.reason).toContain("lines") expect(message.startLine).toBeUndefined() }) it("should show indentation mode snippet with offset fallback", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithIndentation.mockReturnValue({ content: "result", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute( { path: "test.ts", mode: "indentation", offset: 7, } as any, mockTask as any, callbacks, ) const askCall = mockTask.ask.mock.calls[0] const message = JSON.parse(askCall[1]) expect(message.reason).toContain("indentation mode at line 7") }) }) describe("provider state handling", () => { it("should use default image limits when state is null", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() // Make providerRef return null mockTask.providerRef.deref.mockReturnValue(null) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "1 | content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) // Should still work - uses default limits expect(callbacks.pushToolResult).toHaveBeenCalled() }) it("should use default limits when state has no image config", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockTask.providerRef.deref.mockReturnValue({ getState: vi.fn().mockResolvedValue({}), }) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) mockedReadWithSlice.mockReturnValue({ content: "1 | content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalled() }) }) describe("error handling edge cases", () => { it("should handle unknown error types (non-Error)", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsStat.mockRejectedValue("string error") await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) expect(mockTask.didToolFailInCurrentTurn).toBe(true) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("Error")) }) it("should set didToolFailInCurrentTurn on rooignore block", async () => { const mockTask = createMockTask({ rooIgnoreAllowed: false }) const callbacks = createMockCallbacks() await readFileTool.execute({ path: "blocked.ts" }, mockTask as any, callbacks) expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) it("should set didToolFailInCurrentTurn on directory read", async () => { const mockTask = createMockTask() const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue({ isDirectory: () => true } as any) await readFileTool.execute({ path: "src/" }, mockTask as any, callbacks) expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) describe("observation registry", () => { it("records an observation on successful read of an existing file", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() // Override the beforeEach default stat mock with proper BigIntStats. mockedFsStat.mockResolvedValue({ isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), // Cast: the mock only implements the members the tool and versionToken read. } as unknown as Stats) mockedIsBinaryFile.mockResolvedValue(false) // Spy on observe to capture the exact key used (Windows path.resolve may use backslashes). const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) // Verify the tool called observe exactly once with a valid token. expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, calledVersion] = observeSpy.mock.calls[0] expect(calledPath).toContain("existing.ts") expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) // Verify get() returns the same data using the spy-captured key. const obs = reg.get(calledPath) expect(obs).toBeDefined() expect(obs!.version).toBe(calledVersion) }) it("a failed read (absent path) leaves the registry size 0 and does not throw", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsReadFile.mockRejectedValue(new Error("ENOENT")) // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "missing.ts" }, mockTask as unknown as Task, callbacks) // observationRegistry is guaranteed present because we passed it in createMockTask. const reg = mockTask.observationRegistry expect(reg).toBeDefined() expect(reg!.size).toBe(0) }) it("records an observation for legacy-format reads of existing files", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue({ isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), // Cast: the mock only implements the members the tool and versionToken read. } as unknown as Stats) mockedIsBinaryFile.mockResolvedValue(false) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") // Typed legacy (pre-refactor) params: the multi-file format with the // _legacyFormat discriminant (see LegacyReadFileParams). const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy.ts" }], _legacyFormat: true, } // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, calledVersion] = observeSpy.mock.calls[0] expect(calledPath).toContain("legacy.ts") expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) }) it("does not observe when the file mutates between the pre-read and post-read stats", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const preStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } // A mutation lands mid-read: the post-read stat differs. const postStats = { ...preStats, size: BigInt(301) } // Call order: directory check, pre-read stat, post-read stat. mockedFsStat .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) .mockResolvedValueOnce(preStats as unknown as Stats) .mockResolvedValueOnce(postStats as unknown as Stats) mockedIsBinaryFile.mockResolvedValue(false) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "mutated.ts" }, mockTask as unknown as Task, callbacks) // The read itself succeeded, but the target stays unobserved: the content the // model received is not the on-disk state, so observing it would let a later // write match a token the model never saw. expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) expect(mockTask.didToolFailInCurrentTurn).toBe(false) }) it("leaves the target unobserved without failing the read when the pre-read stat fails", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() // Directory check OK; the pre-read stat fails (caught, target unobserved). mockedFsStat .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) .mockRejectedValueOnce(new Error("EACCES")) mockedIsBinaryFile.mockResolvedValue(false) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "stat-fail.ts" }, mockTask as unknown as Task, callbacks) expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) // The read still succeeds — a stat failure never fails the read. expect(mockTask.didToolFailInCurrentTurn).toBe(false) // Assert the pushed payload, not just that something was pushed. const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("File: stat-fail.ts") expect(pushed).toContain("test content") expect(pushed).not.toContain("Error:") }) it("leaves the target unobserved without failing the read when the post-read stat fails", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const okStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } // Directory check and pre-read stat OK; the post-read stat fails. mockedFsStat .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) .mockResolvedValueOnce(okStats as unknown as Stats) .mockRejectedValueOnce(new Error("EACCES")) mockedIsBinaryFile.mockResolvedValue(false) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "post-stat-fail.ts" }, mockTask as unknown as Task, callbacks) expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) expect(mockTask.didToolFailInCurrentTurn).toBe(false) // Assert the pushed payload, not just that something was pushed. const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("File: post-stat-fail.ts") expect(pushed).toContain("test content") expect(pushed).not.toContain("Error:") }) it("legacy format: does not observe when the file mutates between the pre-read and post-read stats", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const preStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } // Call order: directory check, pre-read stat, post-read stat (mutated). mockedFsStat .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) .mockResolvedValueOnce(preStats as unknown as Stats) .mockResolvedValueOnce({ ...preStats, size: BigInt(301) } as unknown as Stats) mockedIsBinaryFile.mockResolvedValue(false) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy-mutated.ts" }], _legacyFormat: true, } // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) expect(mockTask.didToolFailInCurrentTurn).toBe(false) }) it("legacy format: leaves the target unobserved when a stat fails without failing the read", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() // Directory check OK; the pre-read stat fails (caught, target unobserved). mockedFsStat .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) .mockRejectedValueOnce(new Error("EACCES")) mockedIsBinaryFile.mockResolvedValue(false) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy-stat-fail.ts" }], _legacyFormat: true, } // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) expect(mockTask.didToolFailInCurrentTurn).toBe(false) // Assert the pushed payload, not just that something was pushed. const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("File: legacy-stat-fail.ts") expect(pushed).toContain("test content") expect(pushed).not.toContain("Error:") }) it("legacy format: leaves the target unobserved when the post-read stat fails", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const okStats = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } // Directory check and pre-read stat OK; the post-read stat fails. mockedFsStat .mockResolvedValueOnce({ isDirectory: () => false } as unknown as Stats) .mockResolvedValueOnce(okStats as unknown as Stats) .mockRejectedValueOnce(new Error("EACCES")) mockedIsBinaryFile.mockResolvedValue(false) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy-post-stat-fail.ts" }], _legacyFormat: true, } // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).not.toHaveBeenCalled() expect(reg.size).toBe(0) expect(mockTask.didToolFailInCurrentTurn).toBe(false) // Assert the pushed payload, not just that something was pushed. const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("File: legacy-post-stat-fail.ts") expect(pushed).toContain("test content") expect(pushed).not.toContain("Error:") }) it("two separate Task-owned registries are independent", async () => { const regA = new ObservationRegistry() const regB = new ObservationRegistry() regA.observe("/shared.ts", "v1") expect(regA.get("/shared.ts")!.version).toBe("v1") expect(regB.get("/shared.ts")).toBeUndefined() regB.observe("/shared.ts", "v2") expect(regA.get("/shared.ts")!.version).toBe("v1") expect(regB.get("/shared.ts")!.version).toBe("v2") }) it("reads from the same path land in each task's own registry, not the other task's", async () => { // The row above proves two ObservationRegistry instances hold separate entries; it never calls the // tool, so a read that reported its observation into another task's registry would still pass every // line of it. This row drives ReadFileTool.execute twice, once per task, at one path, and asserts the // observation lands in the registry of the task that made the call. const regA = new ObservationRegistry() const regB = new ObservationRegistry() const taskA = createMockTask({ observationRegistry: regA }) const taskB = createMockTask({ observationRegistry: regB }) const callbacksA = createMockCallbacks() const callbacksB = createMockCallbacks() const observeA = vi.spyOn(regA, "observe") const observeB = vi.spyOn(regB, "observe") const statForFirstRead = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), // Cast: the mock only implements the members the tool and versionToken read. } as unknown as Stats mockedFsStat.mockResolvedValue(statForFirstRead) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("isolated\n")) mockedReadWithSlice.mockReturnValue({ content: "1 | isolated", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "isolated.ts" }, taskA as unknown as Task, callbacksA) // A's registry received the observation and B's was not reached at all. expect(observeA).toHaveBeenCalledTimes(1) expect(observeB).not.toHaveBeenCalled() const [keyA, versionA] = observeA.mock.calls[0] expect(regA.get(keyA)!.version).toBe(versionA) expect(regB.get(keyA)).toBeUndefined() // The same path read by B under a different stat, so B's version token is distinguishable from // A's. Both halves are pinned to entries rather than to call counts: B holds its own observation // at the same key and A still holds the one its own read wrote. const statForSecondRead = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(7), size: BigInt(300), mtimeNs: BigInt(9_000_000_000n), ctimeNs: BigInt(5_000_000_000n), // Cast: the mock only implements the members the tool and versionToken read. } as unknown as Stats mockedFsStat.mockResolvedValue(statForSecondRead) await readFileTool.execute({ path: "isolated.ts" }, taskB as unknown as Task, callbacksB) expect(observeB).toHaveBeenCalledTimes(1) const [keyB, versionB] = observeB.mock.calls[0] expect(keyB).toBe(keyA) expect(versionB).not.toBe(versionA) expect(regB.get(keyB)!.version).toBe(versionB) expect(regA.get(keyA)!.version).toBe(versionA) expect(regA.size).toBe(1) expect(regB.size).toBe(1) }) }) describe("read completeness scope (S4b follow-up #46)", () => { // The stat mock only implements the members the tool and versionToken read. const bigintStats = (): Stats => ({ isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), }) as unknown as Stats it("native: a full, untruncated slice read from line 1 records a complete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\n")) mockedReadWithSlice.mockReturnValue({ content: "1 | a\n2 | b", returnedLines: 2, totalLines: 2, wasTruncated: false, includedRanges: [[1, 2]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") await readFileTool.execute({ path: "full.ts" }, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, calledVersion, calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toContain("full.ts") expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) expect(calledComplete).toBe(true) expect(reg.get(calledPath)!.complete).toBe(true) }) it("native: a truncated slice read records a partial observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\nc\nd\ne")) mockedReadWithSlice.mockReturnValue({ content: "1 | a", returnedLines: 1, totalLines: 5, wasTruncated: true, includedRanges: [[1, 1]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") await readFileTool.execute( { path: "trunc.ts", offset: 1, limit: 1 }, mockTask as unknown as Task, callbacks, ) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) expect(reg.get(calledPath)!.complete).toBe(false) }) it("native: a full read whose line content was clipped records a partial observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\n")) mockedReadWithSlice.mockReturnValue({ content: "1 | a\n2 | b", returnedLines: 2, totalLines: 2, wasTruncated: false, hasClippedLines: true, includedRanges: [[1, 2]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") await readFileTool.execute({ path: "clipped.ts" }, mockTask as unknown as Task, callbacks) const [, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) // Every line was returned, so the notice must not point at a next // offset that is beyond the file. const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("clipped in this view") expect(pushed).not.toContain("To read more") // The notice is added on top of the read, it does not replace it. expect(pushed).toContain("1 | a") }) it("native: the clipped notice leaves the first numbered line at column 0", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\n")) mockedReadWithSlice.mockReturnValue({ content: "1 | a\n2 | b", returnedLines: 2, totalLines: 2, wasTruncated: false, hasClippedLines: true, includedRanges: [[1, 2]], }) await readFileTool.execute({ path: "clipped-cols.ts" }, mockTask as unknown as Task, callbacks) const pushed = String(callbacks.pushToolResult.mock.calls[0][0]) const responseLines = pushed.split("\n") const noticeLine = responseLines.findIndex((line) => line.includes("clipped in this view")) expect(noticeLine).toBeGreaterThanOrEqual(0) // The read follows the notice on the very next line, at column 0. The // previous shape joined the two with a template continuation line, which // put this function's own indentation into the response: the first numbered // line arrived indented, and an exact-match edit against a line number the // model can see has to reproduce tabs it was never shown. expect(responseLines[noticeLine + 1]).toBe("1 | a") expect(responseLines[noticeLine + 2]).toBe("2 | b") expect(pushed).not.toContain("\n\t") }) it("native: a clipped slice that started past line 1 reports the range it covered", async () => { // Not truncated does not mean complete: a slice that begins at offset 4 and // stops at the last line returned the tail only. Claiming "read in full" here // is what hides the first three lines from whatever reads the notice. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\nc\nd\ne")) mockedReadWithSlice.mockReturnValue({ content: "4 | d\n5 | e", returnedLines: 2, totalLines: 5, wasTruncated: false, hasClippedLines: true, includedRanges: [[4, 5]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") await readFileTool.execute( { path: "tail.ts", offset: 4, limit: 2 }, mockTask as unknown as Task, callbacks, ) const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("clipped in this view") expect(pushed).toContain("Lines 4-5 of 5 total lines") expect(pushed).not.toContain("The file was read in full") // Still no next-offset hint: nothing was omitted after the slice. expect(pushed).not.toContain("To read more") expect(pushed).toContain("4 | d") const [, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) }) it("native: a clipped read that covered the whole file still says it read in full", async () => { // The other half of the contract: the range sentence must not replace the // accurate statement when the slice really did cover the file. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\nc")) mockedReadWithSlice.mockReturnValue({ content: "1 | a\n2 | b\n3 | c", returnedLines: 3, totalLines: 3, wasTruncated: false, hasClippedLines: true, includedRanges: [[1, 3]], }) await readFileTool.execute({ path: "whole.ts" }, mockTask as unknown as Task, callbacks) const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("The file was read in full, but the clipped lines were not shown in full.") expect(pushed).not.toContain("total lines were shown") }) it("native: a truncated slice that also clipped a line reports both notices", async () => { // A long line inside a slice that also cut lines off is a plausible case, // and the response has to say both things. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\nc")) mockedReadWithSlice.mockReturnValue({ content: "1 | a\n2 | b", returnedLines: 2, totalLines: 3, wasTruncated: true, hasClippedLines: true, includedRanges: [[1, 2]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") await readFileTool.execute({ path: "both.ts" }, mockTask as unknown as Task, callbacks) const [, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("Showing lines 1-2 of 3 total lines") expect(pushed).toContain("clipped in this view") }) it("native: an offset read that is not truncated still records a partial observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\nc\nd\ne")) mockedReadWithSlice.mockReturnValue({ content: "4 | d\n5 | e", returnedLines: 2, totalLines: 5, wasTruncated: false, includedRanges: [[4, 5]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") await readFileTool.execute( { path: "offset.ts", offset: 4, limit: 2 }, mockTask as unknown as Task, callbacks, ) expect(observeSpy).toHaveBeenCalledTimes(1) const [_calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) }) it("native: an indentation-mode block read records a partial observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("function f() { return 1 }")) mockedReadWithIndentation.mockReturnValue({ content: "10 | function f() {", wasTruncated: false, includedRanges: [[10, 20]], totalLines: 100, returnedLines: 11, }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") await readFileTool.execute( { path: "indent.ts", mode: "indentation" }, mockTask as unknown as Task, callbacks, ) expect(observeSpy).toHaveBeenCalledTimes(1) const [_calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) }) it("legacy: a line-range read records a partial observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\nc\nd\ne")) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "ranges.ts", lineRanges: [{ start: 2, end: 4 }] }], _legacyFormat: true, } await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toContain("ranges.ts") expect(calledComplete).toBe(false) }) it("legacy: a full, untruncated slice read records a complete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb")) mockedReadWithSlice.mockReturnValue({ content: "1 | a\n2 | b", returnedLines: 2, totalLines: 2, wasTruncated: false, includedRanges: [[1, 2]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy-full.ts" }], _legacyFormat: true, } await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [_calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(true) // Nothing was omitted and nothing was clipped, so no note is added. const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).not.toContain("clipped in this view") expect(pushed).not.toContain("total lines") }) it("legacy: a full read with a clipped line records a partial observation and reports the clipping", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb")) mockedReadWithSlice.mockReturnValue({ content: "1 | a\n2 | b", returnedLines: 2, totalLines: 2, wasTruncated: false, hasClippedLines: true, includedRanges: [[1, 2]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy-clipped.ts" }], _legacyFormat: true, } await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) const [, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) // Every line was returned, so the note reports the clipping instead of // a showing-N-of-N count that would point past the file. const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("clipped in this view") expect(pushed).not.toContain("showing 2 of 2 total lines") }) it("legacy: a truncated slice that also clipped a line reports both notices", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\nc")) mockedReadWithSlice.mockReturnValue({ content: "1 | a\n2 | b", returnedLines: 2, totalLines: 3, wasTruncated: true, hasClippedLines: true, includedRanges: [[1, 2]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy-both.ts" }], _legacyFormat: true, } await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) const [, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("showing 2 of 3 total lines") expect(pushed).toContain("clipped in this view") }) it("legacy: a slice truncated to the default limit records a partial observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a\nb\nc")) mockedReadWithSlice.mockReturnValue({ content: "1 | a", returnedLines: 1, totalLines: 5000, wasTruncated: true, includedRanges: [[1, 1]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy-trunc.ts" }], _legacyFormat: true, } await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [_calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) // Lines were omitted here, so the note reports the omitted range rather // than clipping. const pushed = callbacks.pushToolResult.mock.calls[0][0] expect(pushed).toContain("showing 1 of 5000 total lines") }) it("native: a read whose bytes did not survive the UTF-8 decode records a partial observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() // 0xFF is not valid UTF-8, so the model receives U+FFFD instead of the byte. const raw = Buffer.from([0x61, 0xff]) mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(raw) mockedReadWithSlice.mockReturnValue({ content: "1 | a\uFFFD", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") await readFileTool.execute({ path: "lossy.ts" }, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) expect(reg.get(calledPath)!.complete).toBe(false) }) it("legacy: a read whose bytes did not survive the UTF-8 decode records a partial observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const raw = Buffer.from([0x61, 0xff]) mockedFsStat.mockResolvedValue(bigintStats()) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(raw) mockedReadWithSlice.mockReturnValue({ content: "1 | a\uFFFD", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy-lossy.ts" }], _legacyFormat: true, } await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) expect(reg.get(calledPath)!.complete).toBe(false) }) }) }) })