From 206463d6bc2e1f49975145ed3c1990db42a97662 Mon Sep 17 00:00:00 2001 From: Dallin Romney Date: Tue, 29 Jul 2025 19:37:17 +0900 Subject: [PATCH] feat: search and replace tool preview and functionality --- src/permissions/types.ts | 3 + src/streamChatResponse.ts | 137 ++++++++++----- src/tools/fetch.ts | 11 ++ src/tools/formatters.test.ts | 15 +- src/tools/index.ts | 53 +++--- src/tools/listFiles.ts | 16 +- src/tools/readFile.ts | 13 +- src/tools/runTerminalCommand.ts | 15 ++ src/tools/searchAndReplace/index.ts | 152 ++++++++--------- src/tools/searchAndReplace/parseArgs.ts | 34 ++++ src/tools/searchCode.ts | 41 ++++- src/tools/types.ts | 26 +++ src/tools/viewDiff.ts | 17 +- src/tools/writeFile.ts | 67 +++++++- src/ui/TUIChat.tsx | 1 + src/ui/components/ToolPermissionSelector.tsx | 14 +- src/ui/components/ToolPreview.tsx | 166 ++++--------------- src/ui/hooks/useChat.ts | 6 +- 18 files changed, 477 insertions(+), 310 deletions(-) create mode 100644 src/tools/searchAndReplace/parseArgs.ts diff --git a/src/permissions/types.ts b/src/permissions/types.ts index 081e99803..a4938f469 100644 --- a/src/permissions/types.ts +++ b/src/permissions/types.ts @@ -1,3 +1,5 @@ +import { ToolCallPreview } from "../tools/types.js"; + export type PermissionPolicy = "allow" | "ask" | "exclude"; export interface ToolPermissionPolicy { @@ -17,6 +19,7 @@ export interface ToolPermissions { export interface ToolCallRequest { name: string; arguments: Record; + preview?: ToolCallPreview[]; } export interface PermissionCheckResult { diff --git a/src/streamChatResponse.ts b/src/streamChatResponse.ts index 242e30d83..31fd36fc6 100644 --- a/src/streamChatResponse.ts +++ b/src/streamChatResponse.ts @@ -12,17 +12,25 @@ import { MCPService } from "./mcp.js"; import { checkToolPermission, filterExcludedTools, + ToolCallRequest, } from "./permissions/index.js"; import { toolPermissionManager } from "./permissions/permissionManager.js"; import telemetryService from "./telemetry/telemetryService.js"; import { calculateTokenCost } from "./telemetry/utils.js"; import { executeToolCall } from "./tools.js"; -import { BUILTIN_TOOLS } from "./tools/index.js"; +import { + BUILTIN_TOOLS, + getAvailableTools, + Tool, + ToolCall, + validateToolCallArgsPresent, +} from "./tools/index.js"; import { chatCompletionStreamWithBackoff, withExponentialBackoff, } from "./util/exponentialBackoff.js"; import logger from "./util/logger.js"; +import { PreprocessedToolCall, ToolCallPreview } from "./tools/types.js"; dotenv.config(); @@ -100,18 +108,10 @@ export interface StreamCallbacks { onToolPermissionRequest?: ( toolName: string, toolArgs: any, - requestId: string + requestId: string, + preview?: ToolCallPreview[] ) => void; } - -interface ToolCall { - id: string; - name: string; - arguments: any; - argumentsStr: string; - startNotified: boolean; -} - function getDefaultCompletionOptions( opts?: CompletionOptions ): Partial { @@ -239,7 +239,7 @@ async function processStreamingResponse( hasToolCalls = true; for (const toolCallDelta of choice.delta.tool_calls) { let toolCallId: string | undefined; - + // If we have an ID, use it and map the index if (toolCallDelta.id) { toolCallId = toolCallDelta.id; @@ -250,12 +250,14 @@ async function processStreamingResponse( // No ID, but we have an index - look up the ID from our map toolCallId = indexToIdMap.get(toolCallDelta.index); } - + if (!toolCallId) { - logger.warn("Tool call delta without ID or valid index mapping", { toolCallDelta }); + logger.warn("Tool call delta without ID or valid index mapping", { + toolCallDelta, + }); continue; } - + // Create tool call entry if it doesn't exist if (!toolCallsMap.has(toolCallId)) { toolCallsMap.set(toolCallId, { @@ -359,7 +361,7 @@ async function processStreamingResponse( const toolCalls = Array.from(toolCallsMap.values()); // Validate tool calls have complete arguments - const validToolCalls = toolCalls.filter((tc) => { + const preprocessedToolCalls = toolCalls.filter((tc) => { if (!tc.arguments || !tc.name) { logger.error("Incomplete tool call", { id: tc.id, @@ -378,8 +380,8 @@ async function processStreamingResponse( return { content: aiResponse, finalContent: finalContent, - toolCalls: validToolCalls, - shouldContinue: validToolCalls.length > 0, + toolCalls: preprocessedToolCalls, + shouldContinue: preprocessedToolCalls.length > 0, }; } @@ -464,8 +466,70 @@ export async function streamChatResponse( tool_calls: toolCallsForHistory, }); - // Execute tool calls + const availableTools: Tool[] = + toolCalls.length > 0 ? await getAvailableTools() : []; + + // Run pre-permission args processing for tool calls + // If pre-processing fails we can just insert failure + // If it succeeds, we ask for permissions + const preProcessedToolCalls: PreprocessedToolCall[] = []; for (const toolCall of toolCalls) { + const startTime = Date.now(); + try { + const tool = availableTools.find((t) => t.name === toolCall.name); + if (!tool) { + throw new Error(`Tool ${toolCall.name} not found`); + } + validateToolCallArgsPresent(toolCall, tool); + const preprocessedCall: PreprocessedToolCall = { + ...toolCall, + tool, + }; + if (tool.preprocess) { + logger.debug("Preprocessing tool call args", { + name: toolCall.name, + arguments: toolCall.arguments, + }); + const preprocessed = await tool.preprocess(toolCall.arguments); + preprocessedCall.preprocessResult = preprocessed; + } + preProcessedToolCalls.push(preprocessedCall); + } catch (error) { + if (callbacks?.onToolStart) { + callbacks.onToolStart(toolCall.name, toolCall.arguments); + } + + const errorMessage = `Error processing tool call: ${ + error instanceof Error ? error.message : String(error) + }`; + + logger.error("Invalid tool call", { + name: toolCall.name, + error: errorMessage, + }); + + const duration = Date.now() - startTime; + telemetryService.logToolResult( + toolCall.name, + false, + duration, + errorMessage + ); + + chatHistory.push({ + role: "tool", + tool_call_id: toolCall.id, + content: errorMessage, + }); + + if (callbacks?.onToolError) { + callbacks.onToolError(errorMessage, toolCall.name); + } + } + } + + // Execute tool calls + for (const toolCall of preProcessedToolCalls) { try { logger.debug("Checking tool permissions", { name: toolCall.name, @@ -473,11 +537,7 @@ export async function streamChatResponse( }); // Check tool permissions - const permissionCheck = checkToolPermission({ - name: toolCall.name, - arguments: toolCall.arguments, - }); - + const permissionCheck = checkToolPermission(toolCall); // Notify tool start immediately - before permission check // This ensures the UI shows the tool call even if it's rejected @@ -493,15 +553,17 @@ export async function streamChatResponse( // Request permission from user if (callbacks?.onToolPermissionRequest) { // Use the proper toolPermissionManager API - const toolCallRequest = { + const toolCallRequest: ToolCallRequest = { name: toolCall.name, - arguments: toolCall.arguments, + arguments: + toolCall.preprocessResult?.args ?? toolCall.arguments, + preview: toolCall.preprocessResult?.preview, }; - + // Set up listener for permissionRequested event const handlePermissionRequested = (event: { requestId: string; - toolCall: { name: string; arguments: any }; + toolCall: ToolCallRequest; }) => { if (event.toolCall.name === toolCall.name) { toolPermissionManager.off( @@ -512,21 +574,21 @@ export async function streamChatResponse( callbacks.onToolPermissionRequest!( event.toolCall.name, event.toolCall.arguments, - event.requestId + event.requestId, + event.toolCall.preview ); } }; - + toolPermissionManager.on( "permissionRequested", handlePermissionRequested ); - + // Request permission using the proper API - const permissionResult = await toolPermissionManager.requestPermission( - toolCallRequest - ); - + const permissionResult = + await toolPermissionManager.requestPermission(toolCallRequest); + approved = permissionResult.approved; } else { // Fallback: deny if no UI callback available @@ -561,10 +623,7 @@ export async function streamChatResponse( arguments: toolCall.arguments, }); - const toolResult = await executeToolCall({ - name: toolCall.name, - arguments: toolCall.arguments, - }); + const toolResult = await executeToolCall(toolCall); chatHistory.push({ role: "tool", diff --git a/src/tools/fetch.ts b/src/tools/fetch.ts index f075feca8..6ad9fc22a 100644 --- a/src/tools/fetch.ts +++ b/src/tools/fetch.ts @@ -46,6 +46,17 @@ export const fetchTool: Tool = { }, }, readonly: true, + preprocess: async (args) => { + return { + preview: [ + { + type: "text", + content: `Will fetch: ${args.url}`, + }, + ], + args, + }; + }, run: async (args: { url: string; timeout?: number }): Promise => { const { url, timeout = 10000 } = args; diff --git a/src/tools/formatters.test.ts b/src/tools/formatters.test.ts index 8f1ddc307..9e35cbd68 100644 --- a/src/tools/formatters.test.ts +++ b/src/tools/formatters.test.ts @@ -16,8 +16,7 @@ describe("formatToolCall", () => { 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"); + expect(formatToolCall("non_existent_tool", null)).toBe("non_existent_tool"); }); it("should format tool name with relative path argument", () => { @@ -31,9 +30,11 @@ describe("formatToolCall", () => { it("should convert absolute paths to relative paths", () => { expect( - formatToolCall("write_file", { filepath: "/Users/test/project/README.md" }) + 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", @@ -79,7 +80,9 @@ describe("formatToolArgument", () => { }); it("should convert absolute paths to relative", () => { - expect(formatToolArgument("/Users/test/project/README.md")).toBe("README.md"); + expect(formatToolArgument("/Users/test/project/README.md")).toBe( + "README.md" + ); expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe( "src/index.ts" ); @@ -95,4 +98,4 @@ describe("formatToolArgument", () => { expect(formatToolArgument(true)).toBe("true"); expect(formatToolArgument({ key: "value" })).toBe("[object Object]"); }); -}); \ No newline at end of file +}); diff --git a/src/tools/index.ts b/src/tools/index.ts index 00a1a527b..2c847ca63 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -7,15 +7,22 @@ import { fetchTool } from "./fetch.js"; import { listFilesTool } from "./listFiles.js"; import { readFileTool } from "./readFile.js"; import { runTerminalCommandTool } from "./runTerminalCommand.js"; +import { searchAndReplaceInFileTool } from "./searchAndReplace/index.js"; import { searchCodeTool } from "./searchCode.js"; -import { type Tool, type ToolParameters } from "./types.js"; +import { + type Tool, + type ToolParameters, + type ToolCall, + PreprocessedToolCall, +} from "./types.js"; import { writeFileTool } from "./writeFile.js"; -export type { Tool, ToolParameters }; +export type { Tool, ToolParameters, ToolCall }; const ALL_BUILTIN_TOOLS: Tool[] = [ readFileTool, writeFileTool, + searchAndReplaceInFileTool, listFilesTool, searchCodeTool, runTerminalCommandTool, @@ -110,12 +117,7 @@ function convertInputSchemaToParameters(inputSchema: any): ToolParameters { return parameters; } -export async function executeToolCall(toolCall: { - name: string; - arguments: Record; -}): Promise { - const startTime = Date.now(); - +export async function getAvailableTools() { const args = parseArgs(); let mcpTools: Tool[] = []; @@ -148,32 +150,27 @@ export async function executeToolCall(toolCall: { } const allTools: Tool[] = [...BUILTIN_TOOLS, ...mcpTools]; + return allTools; +} - const tool = allTools.find((t) => t.name === toolCall.name); - - if (!tool) { - const duration = Date.now() - startTime; - telemetryService.logToolResult( - toolCall.name, - false, - duration, - `Tool "${toolCall.name}" not found` - ); - return `Error: Tool "${toolCall.name}" not found`; - } - +export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) { for (const [paramName, paramDef] of Object.entries(tool.parameters)) { if ( paramDef.required && (toolCall.arguments[paramName] === undefined || toolCall.arguments[paramName] === null) ) { - const duration = Date.now() - startTime; - const error = `Required parameter "${paramName}" missing for tool "${toolCall.name}"`; - telemetryService.logToolResult(toolCall.name, false, duration, error); - return `Error: ${error}`; + throw new Error( + `Required parameter "${paramName}" missing for tool "${toolCall.name}"` + ); } } +} + +export async function executeToolCall( + toolCall: PreprocessedToolCall +): Promise { + const startTime = Date.now(); try { logger.debug("Executing tool", { @@ -181,7 +178,11 @@ export async function executeToolCall(toolCall: { arguments: toolCall.arguments, }); - const result = await tool.run(toolCall.arguments); + // IMPORTANT: if preprocessed args are present, uses preprocessed args instead of original args + // Preprocessed arg names may be different + const result = await toolCall.tool.run( + toolCall.preprocessResult?.args ?? toolCall.arguments + ); const duration = Date.now() - startTime; telemetryService.logToolResult( diff --git a/src/tools/listFiles.ts b/src/tools/listFiles.ts index 86182d5ce..6d4076f80 100644 --- a/src/tools/listFiles.ts +++ b/src/tools/listFiles.ts @@ -1,6 +1,7 @@ import * as fs from "fs"; import * as path from "path"; import { Tool } from "./types.js"; +import { formatToolArgument } from "./formatters.js"; // List files in a directory export const listFilesTool: Tool = { @@ -15,6 +16,19 @@ export const listFilesTool: Tool = { }, }, readonly: true, + preprocess: async (args) => { + return { + args, + preview: [ + { + type: "text", + content: args.directory + ? `Will list files in: ${formatToolArgument(args.directory)}` + : "Will list files in current directory", + }, + ], + }; + }, run: async (args: { dirpath: string }): Promise => { try { if (!fs.existsSync(args.dirpath)) { @@ -41,4 +55,4 @@ export const listFilesTool: Tool = { }`; } }, -}; \ No newline at end of file +}; diff --git a/src/tools/readFile.ts b/src/tools/readFile.ts index 95769aa71..8f6a289fe 100644 --- a/src/tools/readFile.ts +++ b/src/tools/readFile.ts @@ -1,5 +1,6 @@ import * as fs from "fs"; import { Tool } from "./types.js"; +import { formatToolCall } from "./formatters.js"; export const readFileTool: Tool = { name: "read_file", @@ -13,6 +14,12 @@ export const readFileTool: Tool = { }, }, readonly: true, + preprocess: async (args) => { + return { + args, + preview: [{ type: "text", content: formatToolCall("read_file", args) }], + }; + }, run: async (args: { filepath: string }): Promise => { try { if (!fs.existsSync(args.filepath)) { @@ -21,7 +28,9 @@ export const readFileTool: Tool = { const content = fs.readFileSync(args.filepath, "utf-8"); return `Content of ${args.filepath}:\n${content}`; } catch (error) { - return `Error reading file: ${error instanceof Error ? error.message : String(error)}`; + return `Error reading file: ${ + error instanceof Error ? error.message : String(error) + }`; } }, -}; \ No newline at end of file +}; diff --git a/src/tools/runTerminalCommand.ts b/src/tools/runTerminalCommand.ts index a98898bf8..bf8c06246 100644 --- a/src/tools/runTerminalCommand.ts +++ b/src/tools/runTerminalCommand.ts @@ -18,6 +18,21 @@ export const runTerminalCommandTool: Tool = { }, }, readonly: false, + preprocess: async (args) => { + const truncatedCmd = + args.command.length > 60 + ? args.command.substring(0, 60) + "..." + : args.command; + return { + args, + preview: [ + { + type: "text", + content: `Will run: ${truncatedCmd}`, + }, + ], + }; + }, run: async ({ command }: { command: string }): Promise => { return new Promise((resolve, reject) => { exec(command, (error, stdout, stderr) => { diff --git a/src/tools/searchAndReplace/index.ts b/src/tools/searchAndReplace/index.ts index 65b155732..4328c4fa6 100644 --- a/src/tools/searchAndReplace/index.ts +++ b/src/tools/searchAndReplace/index.ts @@ -3,12 +3,12 @@ import { parseAllSearchReplaceBlocks } from "./parseBlock.js"; import { Tool } from "../types.js"; import { generateDiff } from "../writeFile.js"; import * as fs from "fs"; -import * as path from "path"; import telemetryService from "../../telemetry/telemetryService.js"; import { calculateLinesOfCodeDiff, getLanguageFromFilePath, } from "../../telemetry/utils.js"; +import { parseSearchAndReplaceArgs } from "./parseArgs.js"; export interface SearchAndReplaceInFileArgs { filepath: string; @@ -89,87 +89,87 @@ Each string in the diffs array can contain multiple SEARCH/REPLACE blocks, and a required: true, }, }, + preprocess: async (args) => { + // Get and validate args + const { filepath, diffs } = parseSearchAndReplaceArgs(args); + + // Get current file contents + if (!fs.existsSync(filepath)) { + throw new Error(`file ${filepath} does not exist`); + } + const oldContent = fs.readFileSync(filepath, "utf-8"); + let newContent = oldContent; + + // Parse blocks + const blocks = diffs.map(parseAllSearchReplaceBlocks).flat(); + if (blocks.length === 0) { + throw new Error("No complete search/replace blocks found in any diffs"); + } + + // Apply all replacements sequentially to build the final content + for (let i = 0; i < blocks.length; i++) { + const block = blocks[i]; + const { searchContent, replaceContent } = block; + + if (typeof searchContent === "undefined") { + throw new Error(`No search content defined for block ${i + 1}`); + } + if (typeof replaceContent === "undefined") { + throw new Error(`No replace content defined for block ${i + 1}`); + } + + const match = findSearchMatch(newContent, searchContent); + + if (!match) { + throw new Error( + `Search content not found in block ${i + 1}:\n${searchContent}` + ); + } + + newContent = + newContent.substring(0, match.startIndex) + + replaceContent + + newContent.substring(match.endIndex); + } + + // Get lines for telemetry + const { added, removed } = calculateLinesOfCodeDiff(oldContent, newContent); + const language = getLanguageFromFilePath(filepath); + + if (added > 0) { + telemetryService.recordLinesOfCodeModified("added", added, language); + } + if (removed > 0) { + telemetryService.recordLinesOfCodeModified("removed", removed, language); + } + + const diff = generateDiff(oldContent, newContent, filepath); + return { + args: { + filepath, + newContent, + }, + preview: [ + { + type: "text", + content: "", + }, + { + type: "diff", + content: diff, + }, + ], + }; + }, run: async (args) => { try { - // Get and validate args - const { filepath, diffs } = args; - - if (!filepath || !diffs) { - throw new Error("filepath and diffs args are required"); - } - - if (typeof filepath !== "string") { - throw new Error("filepath must be a string"); - } - - if ( - !Array.isArray(diffs) || - diffs.some((diff) => typeof diff !== "string") - ) { - throw new Error( - "diffs must be an array of string search/replace blocks" - ); - } - - // Get current file contents - const fixedPath = filepath.replace(/\/|\\/g, path.sep); - - if (!fs.existsSync(fixedPath)) { - throw new Error(`file ${filepath} does not exist`); - } - const oldContent = fs.readFileSync(fixedPath, "utf-8"); - let newContent = oldContent; - - // Parse blocks - const blocks = diffs.map(parseAllSearchReplaceBlocks).flat(); - if (blocks.length === 0) { - throw new Error("No complete search/replace blocks found in any diffs"); - } - - // Apply all replacements sequentially to build the final content - for (let i = 0; i < blocks.length; i++) { - const block = blocks[i]; - const { searchContent, replaceContent } = block; - - const match = findSearchMatch(newContent, searchContent || ""); - - if (!match) { - throw new Error( - `Search content not found in block ${i + 1}:\n${searchContent}` - ); - } - - newContent = - newContent.substring(0, match.startIndex) + - (replaceContent || "") + - newContent.substring(match.endIndex); - } - - // Get lines for telemetry - const { added, removed } = calculateLinesOfCodeDiff( - oldContent, - args.content - ); - const language = getLanguageFromFilePath(args.filepath); - - if (added > 0) { - telemetryService.recordLinesOfCodeModified("added", added, language); - } - if (removed > 0) { - telemetryService.recordLinesOfCodeModified( - "removed", - removed, - language - ); - } - - const diff = generateDiff(oldContent, args.content, args.filepath); + fs.writeFileSync(args.filepath, args.newContent, "utf-8"); // Record file operation - return `Successfully wrote to file: ${args.filepath}\n\nDiff:\n${diff}`; + return `Successfully edited ${args.filepath}`; } catch (error) { throw new Error( - `Failed to apply search and replace: ${ + `Failed to edit ${args.filepath}:\n ${ error instanceof Error ? error.message : String(error) }` ); diff --git a/src/tools/searchAndReplace/parseArgs.ts b/src/tools/searchAndReplace/parseArgs.ts new file mode 100644 index 000000000..7fed362bd --- /dev/null +++ b/src/tools/searchAndReplace/parseArgs.ts @@ -0,0 +1,34 @@ +import * as path from "path"; + +export function parseSearchAndReplaceArgs(args: any): { + filepath: string; + diffs: string[]; +} { + const { filepath, diffs: diffsArg } = args; + + if (!filepath || !diffsArg) { + throw new Error("filepath and diffs args are required"); + } + + if (typeof filepath !== "string") { + throw new Error("filepath must be a string"); + } + + const diffs: string[] = []; + if (!Array.isArray(diffsArg)) { + throw new Error("diffs must be an array of string search/replace blocks"); + } + diffsArg.forEach((diff, i) => { + if (typeof diff !== "string") { + throw new Error(`Diff at ${i + 1} is not a string`); + } + diffs.push(diff); + }); + + const fixedPath = filepath.replace(/\/|\\/g, path.sep); + + return { + filepath: fixedPath, + diffs, + }; +} diff --git a/src/tools/searchCode.ts b/src/tools/searchCode.ts index cd3a32694..7da99d67b 100644 --- a/src/tools/searchCode.ts +++ b/src/tools/searchCode.ts @@ -30,6 +30,21 @@ export const searchCodeTool: Tool = { }, }, readonly: true, + preprocess: async (args) => { + const truncatedPattern = + args.pattern.length > 50 + ? args.pattern.substring(0, 50) + "..." + : args.pattern; + return { + args, + preview: [ + { + type: "text", + content: `Will search for: "${truncatedPattern}"`, + }, + ], + }; + }, run: async (args: { pattern: string; path?: string; @@ -56,7 +71,9 @@ export const searchCodeTool: Tool = { } if (!stdout.trim()) { - return `No matches found for pattern "${args.pattern}"${args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""}.`; + return `No matches found for pattern "${args.pattern}"${ + args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" + }.`; } // Split the results into lines and limit the number of results @@ -65,20 +82,28 @@ export const searchCodeTool: Tool = { const limitedLines = lines.slice(0, DEFAULT_MAX_RESULTS); const resultText = limitedLines.join("\n"); - const truncationMessage = truncated - ? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]` + const truncationMessage = truncated + ? `\n\n[Results truncated: showing ${DEFAULT_MAX_RESULTS} of ${lines.length} matches]` : ""; - return `Search results for pattern "${args.pattern}"${args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""}:\n\n${resultText}${truncationMessage}`; + return `Search results for pattern "${args.pattern}"${ + args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" + }:\n\n${resultText}${truncationMessage}`; } catch (error: any) { if (error.code === 1) { - return `No matches found for pattern "${args.pattern}"${args.file_pattern ? ` in files matching "${args.file_pattern}"` : ""}.`; + return `No matches found for pattern "${args.pattern}"${ + args.file_pattern ? ` in files matching "${args.file_pattern}"` : "" + }.`; } - return `Error executing ripgrep: ${error instanceof Error ? error.message : String(error)}`; + return `Error executing ripgrep: ${ + error instanceof Error ? error.message : String(error) + }`; } } catch (error) { - return `Error searching code: ${error instanceof Error ? error.message : String(error)}`; + return `Error searching code: ${ + error instanceof Error ? error.message : String(error) + }`; } }, -}; \ No newline at end of file +}; diff --git a/src/tools/types.ts b/src/tools/types.ts index 231186707..fc3cd9685 100644 --- a/src/tools/types.ts +++ b/src/tools/types.ts @@ -10,11 +10,37 @@ export type ToolParameters = Record< } >; +export interface ToolCallPreview { + type: "text" | "diff"; + content: string; + color?: string; + paddingLeft?: number; +} + +export interface PreprocessToolCallResult { + preview?: ToolCallPreview[]; + args: Record; +} + export interface Tool { name: string; displayName: string; description: string; parameters: ToolParameters; + preprocess?: (args: any) => Promise; run: (args: any) => Promise; readonly?: boolean; // Indicates if the tool is readonly } + +export interface ToolCall { + id: string; + name: string; + arguments: any; + argumentsStr: string; + startNotified: boolean; +} + +export interface PreprocessedToolCall extends ToolCall { + tool: Tool; + preprocessResult?: PreprocessToolCallResult; +} diff --git a/src/tools/viewDiff.ts b/src/tools/viewDiff.ts index a312ebbc1..9b595d91a 100644 --- a/src/tools/viewDiff.ts +++ b/src/tools/viewDiff.ts @@ -18,6 +18,17 @@ export const viewDiffTool: Tool = { }, }, readonly: true, + preprocess: async (args) => { + return { + args, + preview: [ + { + type: "text", + content: "Will show git diff", + }, + ], + }; + }, run: async (args: { path?: string }): Promise => { try { const repoPath = args.path || process.cwd(); @@ -47,7 +58,9 @@ export const viewDiffTool: Tool = { return `Git diff for repository at ${repoPath}:\n\n${stdout}`; } catch (error) { - return `Error running git diff: ${error instanceof Error ? error.message : String(error)}`; + return `Error running git diff: ${ + error instanceof Error ? error.message : String(error) + }`; } }, -}; \ No newline at end of file +}; diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index 4b4cdd56f..de3a829a4 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -6,7 +6,7 @@ import { calculateLinesOfCodeDiff, getLanguageFromFilePath, } from "../telemetry/utils.js"; -import { Tool } from "./types.js"; +import { Tool, ToolCallPreview } from "./types.js"; export function generateDiff( oldContent: string, @@ -41,6 +41,65 @@ export const writeFileTool: Tool = { }, }, readonly: false, + preprocess: async (args) => { + try { + if (fs.existsSync(args.filepath)) { + const oldContent = fs.readFileSync(args.filepath, "utf-8"); + const newContent = args.content; + + const diff = createTwoFilesPatch( + args.filepath, + args.filepath, + oldContent, + newContent, + undefined, + undefined, + { context: 2 } + ); + + return { + args, + preview: [ + { + type: "text", + content: "Preview of changes:", + }, + { + type: "diff", + content: diff, + }, + ], + }; + } + } catch (e) { + // do nothing + } + const lines: string[] = args.content.split("\n"); + const previewLines = lines.slice(0, 3); + + const preview: ToolCallPreview[] = [ + { + type: "text", + content: "New file content:", + }, + ...previewLines.map((line) => ({ + type: "text" as const, + content: line || " ", + paddingLeft: 2, + })), + ]; + if (lines.length > 3) { + preview.push({ + type: "text", + content: `... (${lines.length - 3} more lines)`, + }); + } + + return { + args, + preview, + }; + }, run: async (args: { filepath: string; content: string }): Promise => { try { const dirPath = path.dirname(args.filepath); @@ -76,11 +135,7 @@ export const writeFileTool: Tool = { ); } - const diff = generateDiff(oldContent, args.content, args.filepath); - - // Record file operation - - return `Successfully wrote to file: ${args.filepath}\n\nDiff:\n${diff}`; + return `Successfully wrote to file: ${args.filepath}`; } else { // New file creation - count all lines as added const lineCount = args.content.split("\n").length; diff --git a/src/ui/TUIChat.tsx b/src/ui/TUIChat.tsx index 84eaeecc2..9310be98f 100644 --- a/src/ui/TUIChat.tsx +++ b/src/ui/TUIChat.tsx @@ -361,6 +361,7 @@ const TUIChat: React.FC = ({ toolName={activePermissionRequest.toolName} toolArgs={activePermissionRequest.toolArgs} requestId={activePermissionRequest.requestId} + toolCallPreview={activePermissionRequest.toolCallPreview} onResponse={handleToolPermissionResponse} /> ) : ( diff --git a/src/ui/components/ToolPermissionSelector.tsx b/src/ui/components/ToolPermissionSelector.tsx index 7b31d83d5..40b49253e 100644 --- a/src/ui/components/ToolPermissionSelector.tsx +++ b/src/ui/components/ToolPermissionSelector.tsx @@ -1,7 +1,8 @@ import { Box, Text, useInput } from "ink"; import React, { useState } from "react"; import { formatToolCall } from "../../tools/formatters.js"; -import { DetailedToolPreview, ToolPreview } from "./ToolPreview.js"; +import { ToolPreview } from "./ToolPreview.js"; +import { ToolCallPreview } from "../../tools/types.js"; interface PermissionOption { id: string; @@ -15,6 +16,7 @@ interface ToolPermissionSelectorProps { toolName: string; toolArgs: any; requestId: string; + toolCallPreview?: ToolCallPreview[]; onResponse: ( requestId: string, approved: boolean, @@ -38,6 +40,7 @@ export const ToolPermissionSelector: React.FC = ({ toolName, toolArgs, requestId, + toolCallPreview, onResponse, }) => { const [selectedIndex, setSelectedIndex] = useState(0); @@ -102,12 +105,13 @@ export const ToolPermissionSelector: React.FC = ({ {/* Show preview of what the tool will do */} - + - {/* Show detailed preview if available */} - - Would you like to continue? {PERMISSION_OPTIONS.map((option, index) => { diff --git a/src/ui/components/ToolPreview.tsx b/src/ui/components/ToolPreview.tsx index dc975eaa0..7b0bc1c0d 100644 --- a/src/ui/components/ToolPreview.tsx +++ b/src/ui/components/ToolPreview.tsx @@ -1,12 +1,12 @@ -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 { formatToolCall } from "../../tools/formatters.js"; import { getToolDisplayName } from "../../tools.js"; import { ColoredDiff } from "../ColoredDiff.js"; +import { ToolCallPreview } from "../../tools/types.js"; interface ToolPreviewProps { + toolCallPreview?: ToolCallPreview[]; toolName: string; toolArgs: any; } @@ -15,149 +15,39 @@ interface ToolPreviewProps { * Generates a preview of what a tool will do based on its arguments */ export const ToolPreview: React.FC = ({ + toolCallPreview, 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 "list_files": - if (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; - 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; - return `Will run: ${truncatedCmd}`; - } - return "Will run a terminal command"; - - case "fetch": - if (toolArgs.url) { - return `Will fetch: ${toolArgs.url}`; - } - return "Will fetch from a URL"; - - case "view_diff": - return "Will show git diff"; - - default: - // 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)}`; - } - }; - - return ( - - ⎿ - {getPreview()} - - ); -}; - -/** - * Shows a detailed preview for tools where we can predict the output - */ -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) { + if (toolCallPreview) { return ( - - - - {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) && ( - ... - )} - + + {toolCallPreview.map((preview, index) => { + if (preview.type === "text") { + return ( + + {index === 0 && ⎿ } + {preview.content} + + ); + } else { + return ; + } + })} ); } - // For write operations, show diff preview if file exists - if (toolName === "write_file" && toolArgs.filepath && toolArgs.content) { - try { - 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, - toolArgs.filepath, - oldContent, - newContent, - undefined, - undefined, - { context: 2 } - ); - - return ( - - Preview of changes: - - - ); - } else { - // New file - show content preview - const lines = toolArgs.content.split("\n"); - const preview = lines.slice(0, 3); - - return ( - - New file content: - - {preview.map((line: string, i: number) => ( - - {line || " "} - - ))} - {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"); - return ( - - Content preview ({lines.length} lines) - - ); - } + let message = `Will call ${getToolDisplayName(toolName)}`; + const argCount = Object.keys(toolArgs || {}).length; + if (argCount > 0) { + message += ` with ${argCount} argument${argCount !== 1 ? "s" : ""}`; } - return null; + return ( + + ⎿ + {message} + + ); }; diff --git a/src/ui/hooks/useChat.ts b/src/ui/hooks/useChat.ts index 921e4dad2..130e26f89 100644 --- a/src/ui/hooks/useChat.ts +++ b/src/ui/hooks/useChat.ts @@ -18,6 +18,7 @@ import logger from "../../util/logger.js"; import { initializeChatHistory } from "../../commands/chat.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { DisplayMessage } from "../types.js"; +import { ToolCallPreview } from "../../tools/types.js"; interface UseChatProps { assistant?: AssistantUnrolled; @@ -115,6 +116,7 @@ export function useChat({ toolName: string; toolArgs: any; requestId: string; + toolCallPreview?: ToolCallPreview[]; } | null>(null); // Remote mode polling @@ -557,13 +559,15 @@ export function useChat({ onToolPermissionRequest: ( toolName: string, toolArgs: any, - requestId: string + requestId: string, + toolCallPreview?: ToolCallPreview[] ) => { // Set the active permission request to show the selector setActivePermissionRequest({ toolName, toolArgs, requestId, + toolCallPreview, }); }, };