refactor format tool call

This commit is contained in:
Nate 2025-07-27 11:06:49 -07:00
parent 05941d8e82
commit 37b550c5fb
5 changed files with 192 additions and 93 deletions

View file

@ -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]");
});
});

43
src/tools/formatters.ts Normal file
View file

@ -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);
}

View file

@ -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<ToolPermissionSelectorProps> = ({
}
});
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 (
<Box
@ -89,7 +75,7 @@ export const ToolPermissionSelector: React.FC<ToolPermissionSelectorProps> = ({
borderColor="magenta"
>
<Text color="magenta" bold>
{displayName}({formattedArgs})
{toolCallDisplay}
</Text>
{/* Show preview of what the tool will do */}

View file

@ -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<ToolPreviewProps> = ({ 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<ToolPreviewProps> = ({
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<ToolPreviewProps> = ({ 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<ToolPreviewProps> = ({ toolName, toolArgs })
/**
* Shows a detailed preview for tools where we can predict the output
*/
export const DetailedToolPreview: React.FC<ToolPreviewProps> = ({ toolName, toolArgs }) => {
export const DetailedToolPreview: React.FC<ToolPreviewProps> = ({
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 (
<Box flexDirection="column" marginTop={1}>
<Text color="gray">Preview of changes:</Text>
<Box flexDirection="column" paddingLeft={2}>
<Text color="red">- {toolArgs.old_string.split('\n')[0]}</Text>
<Text color="green">+ {toolArgs.new_string.split('\n')[0]}</Text>
{(toolArgs.old_string.split('\n').length > 1 || toolArgs.new_string.split('\n').length > 1) &&
<Text color="gray"> ...</Text>
}
<Text color="red">- {toolArgs.old_string.split("\n")[0]}</Text>
<Text color="green">+ {toolArgs.new_string.split("\n")[0]}</Text>
{(toolArgs.old_string.split("\n").length > 1 ||
toolArgs.new_string.split("\n").length > 1) && (
<Text color="gray"> ...</Text>
)}
</Box>
</Box>
);
@ -123,7 +109,7 @@ export const DetailedToolPreview: React.FC<ToolPreviewProps> = ({ 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<ToolPreviewProps> = ({ toolName, tool
undefined,
{ context: 2 }
);
return (
<Box flexDirection="column" marginTop={1}>
<Text color="gray">Preview of changes:</Text>
@ -143,24 +129,28 @@ export const DetailedToolPreview: React.FC<ToolPreviewProps> = ({ 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 (
<Box flexDirection="column" marginTop={1}>
<Text color="gray">New file content:</Text>
<Box flexDirection="column" paddingLeft={2}>
{preview.map((line: string, i: number) => (
<Text key={i} color="green">{line || ' '}</Text>
<Text key={i} color="green">
{line || " "}
</Text>
))}
{lines.length > 3 && <Text color="gray">... ({lines.length - 3} more lines)</Text>}
{lines.length > 3 && (
<Text color="gray">... ({lines.length - 3} more lines)</Text>
)}
</Box>
</Box>
);
}
} 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 (
<Box flexDirection="column" marginTop={1}>
<Text color="gray">Content preview ({lines.length} lines)</Text>
@ -170,4 +160,4 @@ export const DetailedToolPreview: React.FC<ToolPreviewProps> = ({ toolName, tool
}
return null;
};
};

View file

@ -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) => [