diff --git a/src/tools/formatters.test.ts b/src/tools/formatters.test.ts new file mode 100644 index 000000000..8f1ddc307 --- /dev/null +++ b/src/tools/formatters.test.ts @@ -0,0 +1,98 @@ +import { jest } from "@jest/globals"; +import { formatToolCall, formatToolArgument } from "./formatters.js"; + +describe("formatToolCall", () => { + const originalCwd = process.cwd(); + + beforeEach(() => { + // Mock process.cwd to return a consistent value + jest.spyOn(process, "cwd").mockReturnValue("/Users/test/project"); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should format tool name without arguments", () => { + expect(formatToolCall("write_file")).toBe("Write"); + expect(formatToolCall("read_file", {})).toBe("Read"); + // edit_file doesn't exist, so it returns the original name + expect(formatToolCall("edit_file", null)).toBe("edit_file"); + }); + + it("should format tool name with relative path argument", () => { + expect(formatToolCall("write_file", { filepath: "README.md" })).toBe( + "Write(README.md)" + ); + expect(formatToolCall("read_file", { filepath: "src/index.ts" })).toBe( + "Read(src/index.ts)" + ); + }); + + it("should convert absolute paths to relative paths", () => { + expect( + formatToolCall("write_file", { filepath: "/Users/test/project/README.md" }) + ).toBe("Write(README.md)"); + + expect( + formatToolCall("read_file", { + filepath: "/Users/test/project/src/components/App.tsx", + }) + ).toBe("Read(src/components/App.tsx)"); + }); + + it("should handle absolute paths outside the project", () => { + expect( + formatToolCall("write_file", { filepath: "/Users/other/file.txt" }) + ).toBe("Write(../../other/file.txt)"); + }); + + it("should handle non-path arguments", () => { + expect(formatToolCall("search_code", { pattern: "TODO" })).toBe( + "Search(TODO)" + ); + expect(formatToolCall("search_code", { pattern: 123 })).toBe("Search(123)"); + }); + + it("should use first argument when multiple are provided", () => { + expect( + formatToolCall("write_file", { + filepath: "test.txt", + content: "Hello world", + }) + ).toBe("Write(test.txt)"); + }); +}); + +describe("formatToolArgument", () => { + beforeEach(() => { + jest.spyOn(process, "cwd").mockReturnValue("/Users/test/project"); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should return empty string for null/undefined", () => { + expect(formatToolArgument(null)).toBe(""); + expect(formatToolArgument(undefined)).toBe(""); + }); + + it("should convert absolute paths to relative", () => { + expect(formatToolArgument("/Users/test/project/README.md")).toBe("README.md"); + expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe( + "src/index.ts" + ); + }); + + it("should preserve relative paths", () => { + expect(formatToolArgument("README.md")).toBe("README.md"); + expect(formatToolArgument("./src/index.ts")).toBe("./src/index.ts"); + }); + + it("should handle non-string values", () => { + expect(formatToolArgument(123)).toBe("123"); + expect(formatToolArgument(true)).toBe("true"); + expect(formatToolArgument({ key: "value" })).toBe("[object Object]"); + }); +}); \ No newline at end of file diff --git a/src/tools/formatters.ts b/src/tools/formatters.ts new file mode 100644 index 000000000..12fe7ab00 --- /dev/null +++ b/src/tools/formatters.ts @@ -0,0 +1,43 @@ +import path from "path"; +import { getToolDisplayName } from "./index.js"; + +/** + * Formats a tool call with its arguments for display + * @param toolName The name of the tool + * @param args The tool arguments + * @returns A formatted string like "ToolName(arg)" or just "ToolName" if no args + */ +export function formatToolCall(toolName: string, args?: any): string { + const displayName = getToolDisplayName(toolName); + + if (!args || Object.keys(args).length === 0) { + return displayName; + } + + // Get the first argument value + const firstValue = Object.values(args)[0]; + const formattedValue = formatToolArgument(firstValue); + + return `${displayName}(${formattedValue})`; +} + +/** + * Formats a single tool argument for display + * @param value The argument value + * @returns A formatted string representation of the value + */ +export function formatToolArgument(value: any): string { + if (value === null || value === undefined) { + return ""; + } + + // Convert absolute paths to relative paths + if (typeof value === "string" && path.isAbsolute(value)) { + const workspaceRoot = process.cwd(); + const relativePath = path.relative(workspaceRoot, value); + return relativePath || value; + } + + // Return other values as strings + return String(value); +} \ No newline at end of file diff --git a/src/ui/components/ToolPermissionSelector.tsx b/src/ui/components/ToolPermissionSelector.tsx index 6428ad4e6..9e1e4f019 100644 --- a/src/ui/components/ToolPermissionSelector.tsx +++ b/src/ui/components/ToolPermissionSelector.tsx @@ -1,6 +1,6 @@ import { Box, Text, useInput } from "ink"; import React, { useState } from "react"; -import { getToolDisplayName } from "../../tools.js"; +import { formatToolCall } from "../../tools/formatters.js"; import { ToolPreview, DetailedToolPreview } from "./ToolPreview.js"; interface PermissionOption { @@ -65,21 +65,7 @@ export const ToolPermissionSelector: React.FC = ({ } }); - const formatArgs = (args: any) => { - if (!args || Object.keys(args).length === 0) return ""; - - const firstKey = Object.keys(args)[0]; - const firstValue = args[firstKey]; - - if (typeof firstValue === "string" && firstValue.length > 60) { - return `${firstValue.substring(0, 60)}...`; - } - - return String(firstValue); - }; - - const formattedArgs = formatArgs(toolArgs); - const displayName = getToolDisplayName(toolName); + const toolCallDisplay = formatToolCall(toolName, toolArgs); return ( = ({ borderColor="magenta" > - {displayName}({formattedArgs}) + {toolCallDisplay} {/* Show preview of what the tool will do */} diff --git a/src/ui/components/ToolPreview.tsx b/src/ui/components/ToolPreview.tsx index 9dcea2e54..dc975eaa0 100644 --- a/src/ui/components/ToolPreview.tsx +++ b/src/ui/components/ToolPreview.tsx @@ -1,8 +1,8 @@ -import { Box, Text } from "ink"; -import * as fs from "fs"; -import path from "path"; -import React from "react"; import { createTwoFilesPatch } from "diff"; +import * as fs from "fs"; +import { Box, Text } from "ink"; +import React from "react"; +import { formatToolCall, formatToolArgument } from "../../tools/formatters.js"; import { getToolDisplayName } from "../../tools.js"; import { ColoredDiff } from "../ColoredDiff.js"; @@ -14,58 +14,39 @@ interface ToolPreviewProps { /** * Generates a preview of what a tool will do based on its arguments */ -export const ToolPreview: React.FC = ({ toolName, toolArgs }) => { - const formatPath = (filePath: string) => { - if (path.isAbsolute(filePath)) { - const workspaceRoot = process.cwd(); - const relativePath = path.relative(workspaceRoot, filePath); - return relativePath || filePath; - } - return filePath; - }; - +export const ToolPreview: React.FC = ({ + toolName, + toolArgs, +}) => { const getPreview = () => { + // For tool calls that match the standard format, use formatToolCall + if (toolName === "read_file" || toolName === "write_file" || toolName === "edit_file") { + return formatToolCall(toolName, toolArgs); + } + switch (toolName) { - case "read_file": - if (toolArgs.filepath) { - return `Will read: ${formatPath(toolArgs.filepath)}`; - } - return "Will read a file"; - - case "write_file": - if (toolArgs.filepath) { - const exists = fs.existsSync(toolArgs.filepath); - const action = exists ? "modify" : "create"; - return `Will ${action}: ${formatPath(toolArgs.filepath)}`; - } - return "Will write to a file"; - - case "edit_file": - if (toolArgs.filepath) { - return `Will edit: ${formatPath(toolArgs.filepath)}`; - } - return "Will edit a file"; - case "list_files": if (toolArgs.directory) { - return `Will list files in: ${formatPath(toolArgs.directory)}`; + return `Will list files in: ${formatToolArgument(toolArgs.directory)}`; } return "Will list files in current directory"; case "search_code": if (toolArgs.pattern) { - const truncatedPattern = toolArgs.pattern.length > 50 - ? toolArgs.pattern.substring(0, 50) + "..." - : toolArgs.pattern; + const truncatedPattern = + toolArgs.pattern.length > 50 + ? toolArgs.pattern.substring(0, 50) + "..." + : toolArgs.pattern; return `Will search for: "${truncatedPattern}"`; } return "Will search the codebase"; case "run_terminal_command": if (toolArgs.command) { - const truncatedCmd = toolArgs.command.length > 60 - ? toolArgs.command.substring(0, 60) + "..." - : toolArgs.command; + const truncatedCmd = + toolArgs.command.length > 60 + ? toolArgs.command.substring(0, 60) + "..." + : toolArgs.command; return `Will run: ${truncatedCmd}`; } return "Will run a terminal command"; @@ -83,7 +64,9 @@ export const ToolPreview: React.FC = ({ toolName, toolArgs }) // For unknown tools, show what args will be passed const argCount = Object.keys(toolArgs || {}).length; if (argCount > 0) { - return `Will call ${getToolDisplayName(toolName)} with ${argCount} argument${argCount !== 1 ? 's' : ''}`; + return `Will call ${getToolDisplayName( + toolName + )} with ${argCount} argument${argCount !== 1 ? "s" : ""}`; } return `Will call ${getToolDisplayName(toolName)}`; } @@ -100,18 +83,21 @@ export const ToolPreview: React.FC = ({ toolName, toolArgs }) /** * Shows a detailed preview for tools where we can predict the output */ -export const DetailedToolPreview: React.FC = ({ toolName, toolArgs }) => { +export const DetailedToolPreview: React.FC = ({ + toolName, + toolArgs, +}) => { // For edit operations, we could show a diff preview if we have old_string/new_string if (toolName === "edit_file" && toolArgs.old_string && toolArgs.new_string) { return ( - Preview of changes: - - {toolArgs.old_string.split('\n')[0]} - + {toolArgs.new_string.split('\n')[0]} - {(toolArgs.old_string.split('\n').length > 1 || toolArgs.new_string.split('\n').length > 1) && - ... - } + - {toolArgs.old_string.split("\n")[0]} + + {toolArgs.new_string.split("\n")[0]} + {(toolArgs.old_string.split("\n").length > 1 || + toolArgs.new_string.split("\n").length > 1) && ( + ... + )} ); @@ -123,7 +109,7 @@ export const DetailedToolPreview: React.FC = ({ toolName, tool if (fs.existsSync(toolArgs.filepath)) { const oldContent = fs.readFileSync(toolArgs.filepath, "utf-8"); const newContent = toolArgs.content; - + // Generate a diff preview const diff = createTwoFilesPatch( toolArgs.filepath, @@ -134,7 +120,7 @@ export const DetailedToolPreview: React.FC = ({ toolName, tool undefined, { context: 2 } ); - + return ( Preview of changes: @@ -143,24 +129,28 @@ export const DetailedToolPreview: React.FC = ({ toolName, tool ); } else { // New file - show content preview - const lines = toolArgs.content.split('\n'); + const lines = toolArgs.content.split("\n"); const preview = lines.slice(0, 3); - + return ( New file content: {preview.map((line: string, i: number) => ( - {line || ' '} + + {line || " "} + ))} - {lines.length > 3 && ... ({lines.length - 3} more lines)} + {lines.length > 3 && ( + ... ({lines.length - 3} more lines) + )} ); } } catch (error) { // If we can't read the file, just show a simple preview - const lines = toolArgs.content.split('\n'); + const lines = toolArgs.content.split("\n"); return ( Content preview ({lines.length} lines) @@ -170,4 +160,4 @@ export const DetailedToolPreview: React.FC = ({ toolName, tool } return null; -}; \ No newline at end of file +}; diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index b6a0385d5..d8103ccb4 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -2,7 +2,6 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import { useApp } from "ink"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; -import path from "path"; import { useEffect, useState } from "react"; import { toolPermissionManager } from "../../permissions/permissionManager.js"; import { loadSession, saveSession } from "../../session.js"; @@ -13,7 +12,7 @@ import { } from "../../streamChatResponse.js"; import { constructSystemMessage } from "../../systemMessage.js"; import telemetryService from "../../telemetry/telemetryService.js"; -import { getToolDisplayName } from "../../tools.js"; +import { formatToolCall } from "../../tools/formatters.js"; import { formatError } from "../../util/formatError.js"; import logger from "../../util/logger.js"; @@ -491,23 +490,6 @@ export function useChat({ } }, onToolStart: (toolName: string, toolArgs?: any) => { - const formatToolCall = (name: string, args: any) => { - const displayName = getToolDisplayName(name); - if (!args) return displayName; - - const firstValue = Object.values(args)[0]; - const formatPath = (value: any) => { - if (typeof value === "string" && path.isAbsolute(value)) { - const workspaceRoot = process.cwd(); - const relativePath = path.relative(workspaceRoot, value); - return relativePath || value; - } - return value; - }; - - return `${displayName}(${formatPath(firstValue) || ""})`; - }; - if (currentStreamingMessage && currentStreamingMessage.content) { const messageContent = currentStreamingMessage.content; setMessages((prev) => [