diff --git a/core/tools/implementations/fetchUrlContent.ts b/core/tools/implementations/fetchUrlContent.ts index d2c031d4e..16259780a 100644 --- a/core/tools/implementations/fetchUrlContent.ts +++ b/core/tools/implementations/fetchUrlContent.ts @@ -1,6 +1,34 @@ import { ToolImpl } from "."; import { getUrlContextItems } from "../../context/providers/URLContextProvider"; +const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000; + export const fetchUrlContentImpl: ToolImpl = async (args, extras) => { - return getUrlContextItems(args.url, extras.fetch); + const contextItems = await getUrlContextItems(args.url, extras.fetch); + + // Track truncated content + const truncatedUrls: string[] = []; + + // Check and truncate each context item + const processedItems = contextItems.map((item) => { + if (item.content.length > DEFAULT_FETCH_URL_CHAR_LIMIT) { + truncatedUrls.push(args.url); + return { + ...item, + content: item.content.substring(0, DEFAULT_FETCH_URL_CHAR_LIMIT), + }; + } + return item; + }); + + // Add truncation warning if needed + if (truncatedUrls.length > 0) { + processedItems.push({ + name: "URL content truncation warning", + description: "Informs that URL content was truncated", + content: `The content from ${truncatedUrls.join(", ")} was truncated because it exceeded the ${DEFAULT_FETCH_URL_CHAR_LIMIT} character limit. If you need more content, consider fetching specific sections or using a more targeted approach.`, + }); + } + + return processedItems; }; diff --git a/core/tools/implementations/fetchUrlContent.vitest.ts b/core/tools/implementations/fetchUrlContent.vitest.ts new file mode 100644 index 000000000..9d103893d --- /dev/null +++ b/core/tools/implementations/fetchUrlContent.vitest.ts @@ -0,0 +1,91 @@ +import { expect, test, vi } from "vitest"; +import { fetchUrlContentImpl } from "./fetchUrlContent"; + +vi.mock("../../context/providers/URLContextProvider", () => ({ + getUrlContextItems: vi.fn(), +})); + +import { ToolExtras } from "../.."; +import { getUrlContextItems } from "../../context/providers/URLContextProvider"; +const mockExtras = { + fetch: vi.fn() as any, + ide: {} as any, +} as unknown as ToolExtras; + +test("fetchUrlContent should not truncate content under character limit", async () => { + const shortContent = "This is a short content"; + const mockContextItems = [ + { + name: "Test URL", + description: "Test URL description", + content: shortContent, + }, + ]; + + (getUrlContextItems as any).mockResolvedValue(mockContextItems); + + const result = await fetchUrlContentImpl( + { url: "https://example.com" }, + mockExtras, + ); + + expect(result).toHaveLength(1); + expect(result[0].content).toBe(shortContent); +}); + +test("fetchUrlContent should truncate content exceeding character limit", async () => { + const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000; + // Create a string exceeding the character limit + const longContent = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000); + const mockContextItems = [ + { + name: "Test URL", + description: "Test URL description", + content: longContent, + }, + ]; + + (getUrlContextItems as any).mockResolvedValue(mockContextItems); + + const result = await fetchUrlContentImpl( + { url: "https://example.com" }, + mockExtras, + ); + + expect(result).toHaveLength(2); // Original item + warning + expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); + expect(result[1].name).toBe("URL content truncation warning"); + expect(result[1].content).toContain("was truncated"); + expect(result[1].content).toContain("20000 character limit"); +}); + +test("fetchUrlContent should add truncation warning with multiple truncated items", async () => { + const DEFAULT_FETCH_URL_CHAR_LIMIT = 20000; + // Create strings exceeding the character limit + const longContent1 = "a".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 500); + const longContent2 = "b".repeat(DEFAULT_FETCH_URL_CHAR_LIMIT + 1000); + const mockContextItems = [ + { + name: "Test URL 1", + description: "Test URL description 1", + content: longContent1, + }, + { + name: "Test URL 2", + description: "Test URL description 2", + content: longContent2, + }, + ]; + + (getUrlContextItems as any).mockResolvedValue(mockContextItems); + + const result = await fetchUrlContentImpl( + { url: "https://example.com" }, + mockExtras, + ); + + expect(result).toHaveLength(3); // Two original items + warning + expect(result[0].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); + expect(result[1].content.length).toBe(DEFAULT_FETCH_URL_CHAR_LIMIT); + expect(result[2].name).toBe("URL content truncation warning"); +}); diff --git a/core/tools/implementations/lsTool.ts b/core/tools/implementations/lsTool.ts index 4a7f8bcb5..0418b37f6 100644 --- a/core/tools/implementations/lsTool.ts +++ b/core/tools/implementations/lsTool.ts @@ -2,30 +2,59 @@ import { ToolImpl } from "."; import { walkDir } from "../../indexing/walkDir"; import { resolveRelativePathInDir } from "../../util/ideUtils"; +export function resolveLsToolDirPath(dirPath: string | undefined) { + if (!dirPath || dirPath === ".") { + return "/"; + } + if (dirPath.startsWith(".")) { + return dirPath.slice(1); + } + return dirPath.replace(/\\/g, "/"); +} + +const MAX_LS_TOOL_LINES = 200; + export const lsToolImpl: ToolImpl = async (args, extras) => { - const uri = await resolveRelativePathInDir(args.dirPath, extras.ide); + const dirPath = resolveLsToolDirPath(args?.dirPath); + const uri = await resolveRelativePathInDir(dirPath, extras.ide); if (!uri) { throw new Error( - `Directory ${args.dirPath} not found. Make sure to use forward-slash paths. Do not use e.g. "."`, + `Directory ${args.dirPath} not found. Make sure to use forward-slash paths`, ); } const entries = await walkDir(uri, extras.ide, { returnRelativeUrisPaths: true, include: "both", - recursive: args.recursive ?? false, + recursive: args?.recursive ?? false, }); - const content = - entries.length > 0 - ? entries.join("\n") - : `No files/folders found in ${args.dirPath}`; + const lines = entries.slice(0, MAX_LS_TOOL_LINES); - return [ + let content = + lines.length > 0 + ? lines.join("\n") + : `No files/folders found in ${dirPath}`; + + const contextItems = [ { name: "File/folder list", - description: `Files/folders in ${args.dirPath}`, + description: `Files/folders in ${dirPath}`, content, }, ]; + + if (entries.length > MAX_LS_TOOL_LINES) { + let warningContent = `${entries.length - MAX_LS_TOOL_LINES} ls entries were truncated`; + if (args?.recursive) { + warningContent += ". Try using a non-recursive search"; + } + contextItems.push({ + name: "ls truncation warning", + description: "Informs the model that ls results were truncated", + content: warningContent, + }); + } + + return contextItems; }; diff --git a/core/tools/implementations/lsTool.vitest.ts b/core/tools/implementations/lsTool.vitest.ts new file mode 100644 index 000000000..b697a90c5 --- /dev/null +++ b/core/tools/implementations/lsTool.vitest.ts @@ -0,0 +1,96 @@ +import { expect, test, vi } from "vitest"; +import { ToolExtras } from "../.."; +import * as walkDirModule from "../../indexing/walkDir"; +import { lsToolImpl, resolveLsToolDirPath } from "./lsTool"; + +vi.mock("../../indexing/walkDir"); + +const mockExtras = { + ide: { + fileExists: async (path: string) => true, + getWorkspaceDirs: async () => ["dir1"], + }, +} as unknown as ToolExtras; + +test("resolveLsToolDirPath handles undefined path", () => { + expect(resolveLsToolDirPath(undefined)).toBe("/"); +}); + +test("resolveLsToolDirPath handles empty string", () => { + expect(resolveLsToolDirPath("")).toBe("/"); +}); + +test("resolveLsToolDirPath handles dot", () => { + expect(resolveLsToolDirPath(".")).toBe("/"); +}); + +test("resolveLsToolDirPath handles dot relative", () => { + expect(resolveLsToolDirPath("./hi")).toBe("/hi"); +}); + +test("resolveLsToolDirPath normalizes backslashes to forward slashes", () => { + expect(resolveLsToolDirPath("path\\to\\dir")).toBe("path/to/dir"); +}); + +test("resolveLsToolDirPath preserves forward slashes", () => { + expect(resolveLsToolDirPath("path/to/dir")).toBe("path/to/dir"); +}); + +test("lsToolImpl truncates output when entries exceed MAX_LS_TOOL_LINES", async () => { + // Generate more than MAX_LS_TOOL_LINES entries (which is 200) + const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`); + + // Mock walkDir to return our large array + vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries); + + const result = await lsToolImpl( + { dirPath: "testDir", recursive: true }, + mockExtras, + ); + + // Check that the result contains the truncation message + expect(result.length).toBe(2); + expect(result[0].content).toContain("file1.txt"); + expect(result[0].content).toContain("file199.txt"); + expect(result[1].content).toContain("Try using a non-recursive search"); + expect(result[1].content).toContain("50 ls entries were truncated"); + + // Check that only MAX_LS_TOOL_LINES entries are included + const contentLines = result[0].content.split("\n"); + // Account for the truncation message line + expect(contentLines.length).toBe(200); + + // Check the suggestion to use non-recursive search is included + expect(result[1].content).toContain("Try using a non-recursive search"); +}); + +test("lsToolImpl shows truncation message without suggestion for non-recursive search", async () => { + // Generate more than MAX_LS_TOOL_LINES entries + const mockEntries = Array.from({ length: 250 }, (_, i) => `file${i}.txt`); + + // Mock walkDir to return our large array + vi.spyOn(walkDirModule, "walkDir").mockResolvedValue(mockEntries); + + const result = await lsToolImpl( + { dirPath: "testDir", recursive: false }, + mockExtras, + ); + + // Check that the result contains the truncation message + expect(result.length).toBe(2); + expect(result[1].content).toContain("50 ls entries were truncated"); + + // Check that the suggestion to use non-recursive search is NOT included + expect(result[1].content).not.toContain("Try using a non-recursive search"); +}); + +test("lsToolImpl shows message when no files are found", async () => { + // Mock walkDir to return empty array + vi.spyOn(walkDirModule, "walkDir").mockResolvedValue([]); + + const result = await lsToolImpl({ dirPath: "emptyDir" }, mockExtras); + + // Check that the result contains the "no files found" message + expect(result.length).toBe(1); + expect(result[0].content).toBe("No files/folders found in emptyDir"); +}); diff --git a/core/tools/implementations/searchWeb.ts b/core/tools/implementations/searchWeb.ts index a01212659..c7b64feb3 100644 --- a/core/tools/implementations/searchWeb.ts +++ b/core/tools/implementations/searchWeb.ts @@ -1,8 +1,36 @@ +import { ToolImpl } from "."; import { fetchSearchResults } from "../../context/providers/WebContextProvider"; -import { ToolImpl } from "."; +const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000; export const searchWebImpl: ToolImpl = async (args, extras) => { const webResults = await fetchSearchResults(args.query, 5, extras.fetch); - return webResults; + + // Track truncated results + const truncatedResults: string[] = []; + + // Check and truncate each result + const processedResults = webResults.map((result, index) => { + if (result.content.length > DEFAULT_WEB_SEARCH_CHAR_LIMIT) { + truncatedResults.push( + result.name || result.description || `Result #${index + 1}`, + ); + return { + ...result, + content: result.content.substring(0, DEFAULT_WEB_SEARCH_CHAR_LIMIT), + }; + } + return result; + }); + + // Add truncation warning if needed + if (truncatedResults.length > 0) { + processedResults.push({ + name: "Web search truncation warning", + description: "Informs that search results were truncated", + content: `The content from the following search results was truncated because it exceeded the ${DEFAULT_WEB_SEARCH_CHAR_LIMIT} character limit: ${truncatedResults.join(", ")}. For more detailed information, consider refining your search query.`, + }); + } + + return processedResults; }; diff --git a/core/tools/implementations/searchWeb.vitest.ts b/core/tools/implementations/searchWeb.vitest.ts new file mode 100644 index 000000000..17ddd4925 --- /dev/null +++ b/core/tools/implementations/searchWeb.vitest.ts @@ -0,0 +1,107 @@ +import { expect, test, vi } from "vitest"; +import { searchWebImpl } from "./searchWeb"; + +// Mock the fetchSearchResults function +vi.mock("../../context/providers/WebContextProvider", () => ({ + fetchSearchResults: vi.fn(), +})); +const mockExtras = { + fetch: vi.fn() as any, + ide: {} as any, +} as unknown as ToolExtras; + +import { ToolExtras } from "../.."; +import { fetchSearchResults } from "../../context/providers/WebContextProvider"; + +test("searchWeb should not truncate results under character limit", async () => { + const shortContent = "This is a short search result content"; + const mockSearchResults = [ + { + name: "Result 1", + description: "Search result description 1", + content: shortContent, + }, + { + name: "Result 2", + description: "Search result description 2", + content: shortContent, + }, + ]; + + (fetchSearchResults as any).mockResolvedValue(mockSearchResults); + + const result = await searchWebImpl({ query: "test query" }, mockExtras); + + expect(result).toHaveLength(2); + expect(result[0].content).toBe(shortContent); + expect(result[1].content).toBe(shortContent); +}); + +test("searchWeb should truncate results exceeding character limit", async () => { + const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000; + // Create a string exceeding the character limit + const longContent = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000); + const shortContent = "This is a short search result content"; + const mockSearchResults = [ + { + name: "Result 1", + description: "Search result description 1", + content: longContent, + }, + { + name: "Result 2", + description: "Search result description 2", + content: shortContent, + }, + ]; + + (fetchSearchResults as any).mockResolvedValue(mockSearchResults); + + const result = await searchWebImpl({ query: "test query" }, mockExtras); + + expect(result).toHaveLength(3); // Two results + warning + expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); + expect(result[1].content).toBe(shortContent); + expect(result[2].name).toBe("Web search truncation warning"); + expect(result[2].content).toContain("truncated"); + expect(result[2].content).toContain("Result 1"); + expect(result[2].content).not.toContain("Result 2"); +}); + +test("searchWeb should include all truncated results in the warning", async () => { + const DEFAULT_WEB_SEARCH_CHAR_LIMIT = 8000; + // Create strings exceeding the character limit + const longContent1 = "a".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 500); + const longContent2 = "b".repeat(DEFAULT_WEB_SEARCH_CHAR_LIMIT + 1000); + const shortContent = "This is a short search result content"; + const mockSearchResults = [ + { + name: "Result 1", + description: "Search result description 1", + content: longContent1, + }, + { + name: "Result 2", + description: "Search result description 2", + content: longContent2, + }, + { + name: "Result 3", + description: "Search result description 3", + content: shortContent, + }, + ]; + + (fetchSearchResults as any).mockResolvedValue(mockSearchResults); + + const result = await searchWebImpl({ query: "test query" }, mockExtras); + + expect(result).toHaveLength(4); // Three results + warning + expect(result[0].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); + expect(result[1].content.length).toBe(DEFAULT_WEB_SEARCH_CHAR_LIMIT); + expect(result[2].content).toBe(shortContent); + expect(result[3].name).toBe("Web search truncation warning"); + expect(result[3].content).toContain("Result 1"); + expect(result[3].content).toContain("Result 2"); + expect(result[3].content).not.toContain("Result 3"); +}); diff --git a/core/tools/implementations/viewDiff.ts b/core/tools/implementations/viewDiff.ts index fd1dfdb8a..2b5da1ab8 100644 --- a/core/tools/implementations/viewDiff.ts +++ b/core/tools/implementations/viewDiff.ts @@ -1,15 +1,39 @@ import { ToolImpl } from "."; +import { ContextItem } from "../.."; import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache"; +export const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000; + export const viewDiffImpl: ToolImpl = async (args, extras) => { const diffs = await getDiffsFromCache(extras.ide); // const diffs = await extras.ide.getDiff(true); // TODO includeUnstaged should be an option - return [ + const combinedDiff = diffs.join("\n"); + const diffLines = combinedDiff.split("\n"); + + let truncated = false; + let processedDiff = combinedDiff; + + if (diffLines.length > DEFAULT_GIT_DIFF_LINE_LIMIT) { + truncated = true; + processedDiff = diffLines.slice(0, DEFAULT_GIT_DIFF_LINE_LIMIT).join("\n"); + } + + const contextItems: ContextItem[] = [ { name: "Diff", description: "The current git diff", - content: diffs.join("\n"), + content: processedDiff, }, ]; + + if (truncated) { + contextItems.push({ + name: "Diff truncation warning", + description: "Informs that git diff was truncated", + content: `The git diff was truncated because it exceeded ${DEFAULT_GIT_DIFF_LINE_LIMIT} lines. Consider viewing specific files or focusing on smaller changes.`, + }); + } + + return contextItems; }; diff --git a/core/tools/implementations/viewDiff.vitest.ts b/core/tools/implementations/viewDiff.vitest.ts new file mode 100644 index 000000000..914e3a014 --- /dev/null +++ b/core/tools/implementations/viewDiff.vitest.ts @@ -0,0 +1,87 @@ +import { expect, test, vi } from "vitest"; +import { DEFAULT_GIT_DIFF_LINE_LIMIT, viewDiffImpl } from "./viewDiff"; + +// Mock the getDiffsFromCache function +vi.mock("../../autocomplete/snippets/gitDiffCache", () => ({ + getDiffsFromCache: vi.fn(), +})); + +import { ToolExtras } from "../.."; +import { getDiffsFromCache } from "../../autocomplete/snippets/gitDiffCache"; +const mockExtras = { + fetch: vi.fn() as any, + ide: {} as any, +} as unknown as ToolExtras; + +test("viewDiff should not truncate diffs under line limit", async () => { + // Create a small diff with just a few lines + const smallDiff = [ + "diff --git a/file1.txt b/file1.txt", + "index 1234..5678 100644", + "--- a/file1.txt", + "+++ b/file1.txt", + "@@ -1,3 +1,4 @@", + " line1", + "-line2", + "+line2 modified", + "+line3 added", + ]; + + (getDiffsFromCache as any).mockResolvedValue(smallDiff); + + const result = await viewDiffImpl({}, mockExtras); + + expect(result).toHaveLength(1); // Just the diff, no warning + expect(result[0].name).toBe("Diff"); + expect(result[0].content).toBe(smallDiff.join("\n")); +}); + +test("viewDiff should truncate diffs exceeding line limit", async () => { + // Create a large diff that exceeds the line limit + const largeDiffLines = Array(DEFAULT_GIT_DIFF_LINE_LIMIT + 1000).fill( + "line content", + ); + const largeDiff = [ + "diff --git a/file1.txt b/file1.txt", + "index 1234..5678 100644", + ...largeDiffLines, + ]; + + (getDiffsFromCache as any).mockResolvedValue([largeDiff.join("\n")]); + + const result = await viewDiffImpl({}, mockExtras); + + expect(result).toHaveLength(2); // Diff + warning + + // Count the number of lines in the result + const resultLines = result[0].content.split("\n"); + expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT); + + // Check the warning + expect(result[1].name).toBe("Diff truncation warning"); + expect(result[1].content).toContain("truncated"); + expect(result[1].content).toContain(`${DEFAULT_GIT_DIFF_LINE_LIMIT} lines`); +}); + +test("viewDiff should handle multiple diffs correctly", async () => { + const DEFAULT_GIT_DIFF_LINE_LIMIT = 5000; + + // Create multiple diffs that together exceed the line limit + const diff1Lines = Array(3000).fill("diff1 line"); + const diff2Lines = Array(3000).fill("diff2 line"); + const diff1 = diff1Lines.join("\n"); + const diff2 = diff2Lines.join("\n"); + + (getDiffsFromCache as any).mockResolvedValue([diff1, diff2]); + + const result = await viewDiffImpl({}, mockExtras); + + expect(result).toHaveLength(2); // Diff + warning + + // Count the number of lines in the result + const resultLines = result[0].content.split("\n"); + expect(resultLines.length).toBe(DEFAULT_GIT_DIFF_LINE_LIMIT); + + // Check the warning + expect(result[1].name).toBe("Diff truncation warning"); +});