/** * 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 * as vscode from "vscode" import type { LegacyReadFileParams } from "@roo-code/types" import type { BigIntStats, Stats } from "node:fs" 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 { MAX_LINE_LENGTH } from "../../../core/prompts/tools/native-tools/read_file" 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(), } } const originalWorkspaceFolders = vscode.workspace.workspaceFolders function setWorkspaceFolders(folders: readonly { uri: { fsPath: string } }[] | undefined) { Object.defineProperty(vscode.workspace, "workspaceFolders", { value: folders, configurable: true, writable: true }) } /** Makes the task cwd the workspace, so the tool's real containment check can give both verdicts. */ function useTaskCwdAsWorkspace() { setWorkspaceFolders([{ uri: { fsPath: path.resolve("/test/workspace") } }]) } // ─── Tests ──────────────────────────────────────────────────────────────────── // BigIntStats is a class-backed interface with no public constructor, so a plain-object double // is the only practical way to pin a version token without touching real files. Same shape as // versionToken.spec.ts's local makeStats: single-step downcast from Partial to the full type, // kept test-local here because this file hands the double to a fs.stat mock typed as Stats // (the *Ns fields are what the token reads), which is a last-resort double assertion per AGENTS.md. function makeStats(overrides: Partial = {}): Stats { const base: Partial = { isDirectory: () => false, dev: BigInt(1), ino: BigInt(2), size: BigInt(300), mtimeNs: BigInt(4_000_000_000n), ctimeNs: BigInt(5_000_000_000n), } return { ...base, ...overrides } as unknown as Stats } describe("ReadFileTool", () => { afterEach(() => { setWorkspaceFolders(originalWorkspaceFolders) }) beforeEach(() => { vi.clearAllMocks() // Default mock implementations // Full BigIntStats shape: a partial double makes computeVersionToken throw a // TypeError that its .catch swallows, which launders a mock gap into "no token" // and silently skips observation in every test that does not override this mock. mockedFsStat.mockResolvedValue(makeStats()) 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 }) useTaskCwdAsWorkspace() await readFileTool.execute({ path: "test.ts" }, mockTask as any, callbacks) const [, message] = mockTask.ask.mock.calls[0] expect(JSON.parse(message)).toMatchObject({ isOutsideWorkspace: false }) expect(mockTask.ask).toHaveBeenCalledWith("tool", message, false, undefined, undefined, { fileTargets: [{ absolutePath: path.resolve("/test/workspace", "test.ts"), isOutsideWorkspace: 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("file1 content") mockedFsReadFile.mockResolvedValueOnce("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]], }) useTaskCwdAsWorkspace() 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")) // One complete ask per file, each carrying the target that file is then read from. // The tool uses the default `path` export, which this spec's mock leaves real. const targets = [ { absolutePath: path.resolve("/test/workspace", "file1.ts"), isOutsideWorkspace: false }, { absolutePath: path.resolve("/test/file2.ts"), isOutsideWorkspace: true }, ] expect(mockTask.ask.mock.calls).toEqual( targets.map((target) => [ "tool", expect.any(String), false, undefined, undefined, { fileTargets: [target] }, ]), ) expect(mockedFsReadFile.mock.calls.map(([target]) => target)).toEqual( targets.map(({ absolutePath }) => absolutePath), ) }) describe("batch approval denial", () => { const requestBatchApproval = async (answer: { response: string text?: string approvedIndexes?: number[] files?: string[] }) => { 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 = (answer.files ?? ["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("asks once with a target for every file in the batch", async () => { useTaskCwdAsWorkspace() const { mockTask } = await requestBatchApproval({ response: "yesButtonClicked", files: ["file1.ts", "../outside.ts"], }) expect(mockTask.ask).toHaveBeenCalledTimes(1) const [, message] = mockTask.ask.mock.calls[0] const { batchFiles } = JSON.parse(message) as { batchFiles: { isOutsideWorkspace: boolean }[] } expect(batchFiles.map((file) => file.isOutsideWorkspace)).toEqual([false, true]) expect(mockTask.ask).toHaveBeenCalledWith("tool", message, false, undefined, undefined, { fileTargets: [ { absolutePath: path.resolve("/test/workspace", "file1.ts"), isOutsideWorkspace: false }, { absolutePath: path.resolve("/test/outside.ts"), isOutsideWorkspace: true }, ], }) }) 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("line1\nline2\nline3\nline4\nline5" as any) 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("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(makeStats()) 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).toBe(path.resolve("/test/workspace", "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 empty and flags the tool turn", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() // Full bigint stats, so a swallowed stat failure cannot be what makes this row pass. mockedFsStat.mockResolvedValue(makeStats()) mockedFsReadFile.mockRejectedValue(new Error("ENOENT")) 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: "missing.ts" }, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(0) expect(reg.get(path.resolve("/test/workspace", "missing.ts"))).toBeUndefined() expect(mockTask.didToolFailInCurrentTurn).toBe(true) }) it("observes the token taken before the read, not the one after it", async () => { // A token computed after the read can describe bytes the model never saw: if the // file changes between the read and the stat, the registry ends up holding a newer // token than the content the tool returned, and the write guard would then accept a // stale write. This fixture mutates the file inside the read itself, so the pre-read // and post-read tokens differ and the assertion names which one may be recorded. The // direction is chosen deliberately: a mid-read mutation must mismatch and block the // guarded write, which is the conservative answer for a guard. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() // The directory-check stat and the token stat share this mock. Only the token // lookup passes { bigint: true }, so the mutation flag decides which token shape it // returns; readStarted records whether the read had already happened. let readStarted = false mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => makeStats({ mtimeNs: BigInt(options?.bigint && readStarted ? 9_000_000_000n : 4_000_000_000n), }), ) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockImplementation(async () => { readStarted = true return Buffer.from("content") }) 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) expect(observeSpy).toHaveBeenCalledTimes(1) const [, calledVersion] = observeSpy.mock.calls[0] // 4000000000 is the pre-read mtimeNs; 9000000000 is the mutated file. expect(calledVersion).toBe("1:2:300:4000000000:5000000000") expect(readStarted).toBe(true) }) it("keeps the earlier observation when the context tracker rejects (native path)", async () => { // trackFileContext swallows its own failures in production (FileContextTracker.ts:81-95 puts its // whole body in a try whose catch only console.errors), so a rejection here can only come from // this double. What the case pins is where the read stands when it does: the failure lands in the // surrounding catch, which replaces the not-yet-recorded content with an error row and marks the // turn failed, and observeReadVersion - which sits after the tracker call - never runs, so the // entry from the earlier read stays exactly as it was. An older token mismatches a changed file, // so the leftover blocks a later guarded write rather than green-lighting it. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const fullPath = path.resolve("/test/workspace", "existing.ts") // An observation from an earlier read, so the case can name what a skipped observe leaves: // the older token, not a refreshed one and not an absence. reg.observe(fullPath, "seed:1:2:300:1000000000:1000000001") const observeSpy = vi.spyOn(reg, "observe") mockTask.fileContextTracker.trackFileContext.mockRejectedValueOnce(new Error("tracker exploded")) // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) // The read itself succeeded; the error the model sees is the tracker's. expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("tracker exploded")) expect(String(callbacks.pushToolResult.mock.calls[0][0])).not.toContain("test content") expect(mockTask.didToolFailInCurrentTurn).toBe(true) expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("tracker exploded")) expect(mockTask.fileContextTracker.trackFileContext).toHaveBeenCalledTimes(1) expect(observeSpy).toHaveBeenCalledTimes(0) expect(reg.get(fullPath)?.version).toBe("seed:1:2:300:1000000000:1000000001") }) it("keeps its content and the earlier observation when the tracker rejects (legacy path)", async () => { // The legacy branch reaches the same conclusion by a different route, and the difference is // the part worth pinning: it pushes the file's content into the results before it calls the // tracker, so a rejection there leaves the content in the tool result *and* appends an error // row, while the observation is left exactly as the earlier read put it. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() mockedFsReadFile.mockResolvedValue("legacy content") const reg = mockTask.observationRegistry! const fullPath = path.resolve("/test/workspace", "legacy.ts") reg.observe(fullPath, "seed:1:2:300:1000000000:1000000001") const observeSpy = vi.spyOn(reg, "observe") mockTask.fileContextTracker.trackFileContext.mockRejectedValueOnce(new Error("tracker exploded")) 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(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("1 | test content")) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("Error: tracker exploded"), ) expect(mockTask.didToolFailInCurrentTurn).toBe(true) expect(mockTask.say).toHaveBeenCalledWith("error", expect.stringContaining("tracker exploded")) expect(observeSpy).toHaveBeenCalledTimes(0) expect(reg.get(fullPath)?.version).toBe("seed:1:2:300:1000000000:1000000001") }) it("a failed version-token lookup after a successful read keeps the result and leaves the registry empty", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") // Only computeVersionToken asks for bigint stats, so arm the failure on that // call rather than on call parity, which ties the test to how many stats a read // happens to make: the directory check stays green and only the token lookup // rejects. const okStats = makeStats() mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => { if (options?.bigint === true) { throw new Error("EACCES") } return okStats }) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) // The read itself succeeded: no failure flag and the result carries the file // and its content (not just the path). expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) // The failed token lookup recorded nothing. The registry-wide claim in the name // is measured on the observe entry point against this row's fresh registry, and // the path-level get stays as the concrete symptom. expect(observeSpy).toHaveBeenCalledTimes(0) expect(reg.get(path.resolve("/test/workspace", "existing.ts"))).toBeUndefined() }) it("drops the stale observation when the version-token lookup fails after an earlier successful read", async () => { // Warm-state companion to the cold test above, which starts from an empty // registry. Here the registry already holds a token from a previous read of // the same path, so the failed lookup has to drop it: otherwise the write // guard keeps comparing against a token that no longer describes the file. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const okStats = makeStats() mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("content")) // Each read stats the path twice: once to rule out a directory and once for // the version token. Only the token lookup is made to fail. // Only computeVersionToken asks for bigint stats, so arm the failure on that // call rather than on call parity, which ties the test to how many stats a // read happens to make. let failTokenLookup = false mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => { // Cast: the mock only needs the option the real caller passes. if (failTokenLookup && options?.bigint === true) { throw new Error("EACCES") } return okStats }) // Seed: a successful read records an observation for the resolved path. await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [observedPath, observedVersion] = observeSpy.mock.calls[0] expect(reg.get(observedPath)?.version).toBe(observedVersion) // Drop the seed read's pushed result. Both warm tests keep using the same mock, so // without this the seed read's own call satisfies the content assertions below even // when the token-failure read returns nothing. callbacks.pushToolResult.mockClear() // The next read of the same path loses its token lookup. failTokenLookup = true await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) // The read itself still succeeded: content is preserved, no failure flag. expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("existing.ts")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("content")) // The failed lookup observed nothing and dropped the stale entry. expect(observeSpy).toHaveBeenCalledTimes(1) expect(reg.get(observedPath)).toBeUndefined() }) it("a failed version-token lookup on a legacy read keeps the result and leaves the registry empty", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") // Same shape as the native case, on the legacy multi-file path: only the bigint // stat that computeVersionToken asks for is made to reject. const okStats = makeStats() mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => { if (options?.bigint === true) { throw new Error("EACCES") } return okStats }) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue("legacy content") // The legacy path slices the raw content through readWithSlice, so the slice // mock must carry the legacy content for the result assertion below. mockedReadWithSlice.mockReturnValue({ content: "1 | legacy content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) // 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) // The legacy read succeeded: no failure flag and the result carries the file // and its content (not just the path). expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) // Same claim as the native case: nothing recorded against this row's fresh // registry, plus the path-level get as the concrete symptom. expect(observeSpy).toHaveBeenCalledTimes(0) expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))).toBeUndefined() }) it("drops the stale observation when a legacy read loses its version token after an earlier successful read", async () => { // Warm-state companion on the legacy multi-file path, for the same reason as // the native case above: the entry from the first read must not survive a // token lookup that failed on the second. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") const okStats = makeStats() mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue("legacy content") // The legacy path slices the raw content through readWithSlice. mockedReadWithSlice.mockReturnValue({ content: "1 | legacy content", returnedLines: 1, totalLines: 1, wasTruncated: false, includedRanges: [[1, 1]], }) // Each read stats the path twice: once to rule out a directory and once for // the version token. Only the token lookup is made to fail. // Only computeVersionToken asks for bigint stats, so arm the failure on that // call rather than on call parity, which ties the test to how many stats a // read happens to make. let failTokenLookup = false mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => { // Cast: the mock only needs the option the real caller passes. if (failTokenLookup && options?.bigint === true) { throw new Error("EACCES") } return okStats }) // Typed legacy (pre-refactor) params: the multi-file format with the // _legacyFormat discriminant (see LegacyReadFileParams). const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy.ts" }], _legacyFormat: true, } await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [observedPath, observedVersion] = observeSpy.mock.calls[0] expect(observedPath).toBe(path.resolve("/test/workspace", "legacy.ts")) expect(reg.get(observedPath)?.version).toBe(observedVersion) // Same reason as the native warm test: clear the seed read's result so the two // content assertions can only be satisfied by the token-failure legacy read. callbacks.pushToolResult.mockClear() failTokenLookup = true await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) // The legacy read still succeeded: content is preserved, no failure flag. expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy.ts")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("legacy content")) expect(observeSpy).toHaveBeenCalledTimes(1) expect(reg.get(observedPath)).toBeUndefined() }) it("records an observation for legacy-format reads of existing files", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() // The legacy branch asks fs.readFile for utf8 text, so the double hands back text. mockedFsReadFile.mockResolvedValue("legacy content") mockedFsStat.mockResolvedValue(makeStats()) 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).toBe(path.resolve("/test/workspace", "legacy.ts")) expect(calledVersion).toMatch(/^\d+:\d+:\d+:\d+:\d+$/) }) it("the legacy path takes its token before the read too", async () => { // Same fixture as the native ordering case above, run through the typed legacy params: the // legacy branch has its own stat-then-read pair at ReadFileTool.ts:781, and a token taken // after its read would put a newer token in the registry than the content the model saw. // The file mutates mid-read, so the two tokens differ and the assertion names which one // may be recorded. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() let readStarted = false mockedFsStat.mockImplementation(async (_path: unknown, options?: { bigint?: boolean }) => makeStats({ mtimeNs: BigInt(options?.bigint && readStarted ? 9_000_000_000n : 4_000_000_000n), }), ) mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockImplementation(async () => { readStarted = true return `content` }) const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") 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 [, calledVersion] = observeSpy.mock.calls[0] // 4000000000 is the pre-read mtimeNs; 9000000000 is the mutated file. expect(calledVersion).toBe(`1:2:300:4000000000:5000000000`) expect(readStarted).toBe(true) }) it("a truncated slice read is recorded as an incomplete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\nline 2\nline 3\nline 4\nline 5")) // A view of the file, not the file: lines 2-3 of 5. mockedReadWithSlice.mockReturnValue({ content: "2 | line 2\n3 | line 3", returnedLines: 2, totalLines: 5, wasTruncated: true, includedRanges: [[2, 3]], }) // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute( { path: "existing.ts", mode: "slice", offset: 2, limit: 2 }, mockTask as unknown as Task, callbacks, ) // The read still succeeded and still reports its view of the file. expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("line 2")) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) expect(calledComplete).toBe(false) // What the S4 guard reads: a view must not carry full-file authority. expect(reg.get(calledPath)?.complete).toBe(false) }) it("an untruncated slice that starts past line 1 is recorded as an incomplete observation", async () => { // Every fixture above pairs a partial view with wasTruncated, so none of them can show // that completeness is a claim about coverage rather than about truncation. The local // mock cannot produce the untruncated-past-line-1 shape on its own, so this runs the // real slice reader through the tool: the lowest layer that reaches the observation. const realReader = await vi.importActual< typeof import("../../../integrations/misc/indentation-reader") >("../../../integrations/misc/indentation-reader") const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\nline 2\nline 3\nline 4\nline 5")) // One call only: the tool slices exactly once per read, so the real reader stays scoped // to this test. mockedReadWithSlice.mockImplementationOnce(realReader.readWithSlice) // Five lines, offset 2, limit 10: lines 2-5 come back whole and nothing is cut off, yet // line 1 never reaches the model. await readFileTool.execute( { path: "existing.ts", mode: "slice", offset: 2, limit: 10 }, mockTask as unknown as Task, callbacks, ) expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("2 | line 2")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("5 | line 5")) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.not.stringContaining("IMPORTANT: File content truncated."), ) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.not.stringContaining("1 | line 1")) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) expect(calledComplete).toBe(false) // Not truncated is not the same as complete: a view still must not authorize a // full-file replacement. expect(reg.get(calledPath)?.complete).toBe(false) }) it("a read that returned every line is recorded as a complete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\nline 2")) mockedReadWithSlice.mockReturnValue({ content: "1 | line 1\n2 | line 2", returnedLines: 2, totalLines: 2, wasTruncated: false, includedRanges: [[1, 2]], }) // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(true) expect(reg.get(calledPath)?.complete).toBe(true) }) it("an indentation read that returned every line is recorded as a complete observation", async () => { // The real reader again, so the range shape comes from the reader and not from a // fixture: a single top-level block means the extraction returned the whole file, so // the observation may carry full-file authority. const realReader = await vi.importActual< typeof import("../../../integrations/misc/indentation-reader") >("../../../integrations/misc/indentation-reader") const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\n line 2\n line 3")) mockedReadWithIndentation.mockImplementationOnce(realReader.readWithIndentation) await readFileTool.execute( { path: "existing.ts", mode: "indentation", indentation: { anchor_line: 1 } }, mockTask as unknown as Task, callbacks, ) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) expect(calledComplete).toBe(true) expect(reg.get(calledPath)?.complete).toBe(true) }) it("an indentation read that stopped short of the last line is recorded as an incomplete observation", async () => { // The indentation twin of the case above: a second top-level block makes sibling // exclusion stop the expansion at line 4 of 5, and the reader reports no truncation. So // this row fails on coverage, not on wasTruncated. const realReader = await vi.importActual< typeof import("../../../integrations/misc/indentation-reader") >("../../../integrations/misc/indentation-reader") const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("line 1\n line 2\nline 3\n line 4\nline 5")) mockedReadWithIndentation.mockImplementationOnce(realReader.readWithIndentation) await readFileTool.execute( { path: "existing.ts", mode: "indentation", indentation: { anchor_line: 1 } }, mockTask as unknown as Task, callbacks, ) expect(mockTask.didToolFailInCurrentTurn).toBe(false) // The reader keeps the original leading whitespace, so the pin includes it. expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("4 | line 4")) expect(callbacks.pushToolResult).toHaveBeenCalledWith( expect.stringContaining("Included ranges: 1-4 (total: 5 lines)"), ) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.not.stringContaining("5 | line 5")) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) expect(calledComplete).toBe(false) expect(reg.get(calledPath)?.complete).toBe(false) }) it("a read that clipped a long line is recorded as an incomplete observation", async () => { // One character above the formatter per-line limit: every line number is in the // range and nothing was line-truncated, yet the line came back with its tail // replaced by an ellipsis, so the model never saw the last characters. const realReader = await vi.importActual< typeof import("../../../integrations/misc/indentation-reader") >("../../../integrations/misc/indentation-reader") const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a".repeat(MAX_LINE_LENGTH + 1))) mockedReadWithSlice.mockImplementationOnce(realReader.readWithSlice) await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) expect(mockTask.didToolFailInCurrentTurn).toBe(false) // The clipped tail is what the model was shown. const shown = String(callbacks.pushToolResult.mock.calls[0][0]) expect(shown).toContain("a".repeat(MAX_LINE_LENGTH - 3)) expect(shown).toContain("...") // The characters past the clip never reached the model. expect(shown).not.toContain("a".repeat(MAX_LINE_LENGTH)) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toBe(path.resolve("/test/workspace", "existing.ts")) expect(calledComplete).toBe(false) // Not complete: a clipped view must not authorize a full-file replacement. expect(reg.get(calledPath)?.complete).toBe(false) }) it("a read that ended exactly at the character limit stays a complete observation", async () => { // The boundary the row above leans on: at MAX_LINE_LENGTH the formatter leaves the // line alone, so nothing was lost and full-file authority is the right verdict. const realReader = await vi.importActual< typeof import("../../../integrations/misc/indentation-reader") >("../../../integrations/misc/indentation-reader") const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a".repeat(MAX_LINE_LENGTH))) mockedReadWithSlice.mockImplementationOnce(realReader.readWithSlice) await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) expect(mockTask.didToolFailInCurrentTurn).toBe(false) const shown = String(callbacks.pushToolResult.mock.calls[0][0]) expect(shown).toContain("1 | " + "a".repeat(MAX_LINE_LENGTH)) expect(shown).not.toContain("...") expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(true) expect(reg.get(calledPath)?.complete).toBe(true) }) it("a default legacy read that clipped a long line is recorded as an incomplete observation", async () => { // The legacy path runs its default read through the same slice reader, so a clipped // tail must not buy full-file authority there either. const realReader = await vi.importActual< typeof import("../../../integrations/misc/indentation-reader") >("../../../integrations/misc/indentation-reader") const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockImplementation(async () => "a".repeat(MAX_LINE_LENGTH + 1)) mockedReadWithSlice.mockImplementationOnce(realReader.readWithSlice) const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy.ts" }], _legacyFormat: true, } await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(mockTask.didToolFailInCurrentTurn).toBe(false) const shown = String(callbacks.pushToolResult.mock.calls[0][0]) expect(shown).toContain("a".repeat(MAX_LINE_LENGTH - 3)) expect(shown).toContain("...") expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toBe(path.resolve("/test/workspace", "legacy.ts")) expect(calledComplete).toBe(false) expect(reg.get(calledPath)?.complete).toBe(false) }) it("a whole-file read that clipped one line among several is recorded as an incomplete observation", async () => { // Coverage is intact across the three lines and only the middle one loses its tail. // A guard that looked at the first line only, or at single-line files only, would // still hand this read full-file authority. const realReader = await vi.importActual< typeof import("../../../integrations/misc/indentation-reader") >("../../../integrations/misc/indentation-reader") const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue( Buffer.from(["before", "a".repeat(MAX_LINE_LENGTH + 1), "after"].join("\n")), ) mockedReadWithSlice.mockImplementationOnce(realReader.readWithSlice) await readFileTool.execute({ path: "existing.ts" }, mockTask as unknown as Task, callbacks) expect(mockTask.didToolFailInCurrentTurn).toBe(false) // Every line number came back, including the last one. const shown = String(callbacks.pushToolResult.mock.calls[0][0]) expect(shown).toContain("3 | after") expect(shown).toContain("a".repeat(MAX_LINE_LENGTH - 3)) expect(shown).toContain("...") expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) expect(reg.get(calledPath)?.complete).toBe(false) }) it("an indentation read that clipped a long line is recorded as an incomplete observation", async () => { // The indentation path formats through the same function, so a clipped line there is // the same loss with a different reader in front of it. const realReader = await vi.importActual< typeof import("../../../integrations/misc/indentation-reader") >("../../../integrations/misc/indentation-reader") const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockResolvedValue(Buffer.from("a".repeat(MAX_LINE_LENGTH + 1))) mockedReadWithIndentation.mockImplementationOnce(realReader.readWithIndentation) await readFileTool.execute( { path: "existing.ts", mode: "indentation", indentation: { anchor_line: 1 } }, mockTask as unknown as Task, callbacks, ) expect(mockTask.didToolFailInCurrentTurn).toBe(false) const shown = String(callbacks.pushToolResult.mock.calls[0][0]) expect(shown).toContain("a".repeat(MAX_LINE_LENGTH - 3)) expect(shown).toContain("...") expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(false) expect(reg.get(calledPath)?.complete).toBe(false) }) it("a legacy read whose line ranges leave lines out is recorded as an incomplete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockImplementation(async () => "line 1\nline 2\nline 3\nline 4\nline 5") const legacyParams: LegacyReadFileParams = { files: [{ path: "legacy.ts", lineRanges: [{ start: 2, end: 3 }] }], _legacyFormat: true, } // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(mockTask.didToolFailInCurrentTurn).toBe(false) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("2 | line 2")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.not.stringContaining("line 5")) expect(observeSpy).toHaveBeenCalledTimes(1) const [calledPath, , calledComplete] = observeSpy.mock.calls[0] expect(calledPath).toBe(path.resolve("/test/workspace", "legacy.ts")) expect(calledComplete).toBe(false) expect(reg.get(calledPath)?.complete).toBe(false) }) it("a legacy read that covered every line is recorded as a complete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockImplementation(async () => "line 1\nline 2") mockedReadWithSlice.mockReturnValue({ content: "1 | line 1\n2 | line 2", returnedLines: 2, totalLines: 2, wasTruncated: false, includedRanges: [[1, 2]], }) 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, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(true) expect(reg.get(calledPath)?.complete).toBe(true) }) it("a legacy read whose ranges together cover the file is recorded as a complete observation", async () => { const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockImplementation(async () => "line 1\nline 2\nline 3\nline 4\nline 5") // Out of order and overlapping, yet every line is in the view the model got. const legacyParams: LegacyReadFileParams = { files: [ { path: "legacy.ts", lineRanges: [ { start: 3, end: 5 }, { start: 1, end: 3 }, ], }, ], _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 [, , calledComplete] = observeSpy.mock.calls[0] expect(calledComplete).toBe(true) expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))?.complete).toBe(true) }) it("a fractional legacy line range endpoint is rejected instead of recorded as a complete observation", async () => { // The parser builds legacy ranges with Number(), so a JSON number like 1.5 survives into // executeLegacy. On a two-line file these ranges index lines 0.5 and 0/1: the view the // model got read "1.5 | undefined", and the coverage helper credited the fractional index // a line of its own, so the observation claimed the whole file while line 2 never arrived. const mockTask = createMockTask({ observationRegistry: new ObservationRegistry(), }) const callbacks = createMockCallbacks() const reg = mockTask.observationRegistry! const observeSpy = vi.spyOn(reg, "observe") mockedIsBinaryFile.mockResolvedValue(false) mockedFsReadFile.mockImplementation(async () => "line 1\nline 2") const legacyParams: LegacyReadFileParams = { files: [ { path: "legacy.ts", lineRanges: [ { start: 1.5, end: 2 }, { start: 1, end: 1 }, ], }, ], _legacyFormat: true, } // Cast: the mock task only implements the members ReadFileTool.execute touches. await readFileTool.execute(legacyParams, mockTask as unknown as Task, callbacks) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.stringContaining("whole line numbers")) expect(callbacks.pushToolResult).toHaveBeenCalledWith(expect.not.stringContaining("undefined")) // Rejected before the approval prompt: no ask, no read, and nothing for the guard to trust. expect(mockTask.ask).toHaveBeenCalledTimes(0) expect(mockTask.didToolFailInCurrentTurn).toBe(true) expect(observeSpy).toHaveBeenCalledTimes(0) expect(reg.get(path.resolve("/test/workspace", "legacy.ts"))).toBeUndefined() }) }) }) })