test: preprocess tests

This commit is contained in:
Dallin Romney 2025-07-30 11:12:00 -07:00
parent fa30e245d2
commit ea3de40def
18 changed files with 2185 additions and 222 deletions

View file

@ -62,6 +62,7 @@ This is a CLI tool for Continue Dev that provides an interactive AI-assisted dev
- Configuration in `jest.config.mjs`
- Tests should be written with `.test.ts` extension
- No existing test files found - tests should be added when writing new functionality
- Run tests using `npm run test path/or/pattern`
### Build System

1532
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -10,6 +10,8 @@
},
"scripts": {
"test": "npm run lint && cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"vitest": "vitest run",
"vitest:watch": "vitest watch",
"build": "tsc -p tsconfig.build.json",
"start": "node dist/index.js",
"dev": "tsx src/index.ts",
@ -95,7 +97,8 @@
"supertest": "^7.1.3",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2",
"tsx": "^4.20.3"
"tsx": "^4.20.3",
"vitest": "^3.2.4"
},
"engine": {
"node": ">=18"

View file

@ -4,21 +4,30 @@ import express, { Request, Response } from "express";
import type { ChatCompletionMessageParam } from "openai/resources.mjs";
import path from "path";
import { promisify } from "util";
import {
getAssistantSlug,
} from "../auth/workos.js";
import { getAssistantSlug } from "../auth/workos.js";
import { toolPermissionManager } from "../permissions/permissionManager.js";
import { saveSession } from "../session.js";
import { getService, initializeServices, SERVICE_NAMES } from "../services/index.js";
import { AuthServiceState, ConfigServiceState, ModelServiceState } from "../services/types.js";
import { streamChatResponse, type StreamCallbacks } from "../streamChatResponse.js";
import {
getService,
initializeServices,
SERVICE_NAMES,
} from "../services/index.js";
import {
AuthServiceState,
ConfigServiceState,
ModelServiceState,
} from "../services/types.js";
import {
streamChatResponse,
type StreamCallbacks,
} from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import telemetryService from "../telemetry/telemetryService.js";
import { getToolDisplayName } from "../tools.js";
import { DisplayMessage } from "../ui/types.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { ExtendedCommandOptions } from "./BaseCommandOptions.js";
import { getToolDisplayName } from "../tools/index.js";
const execAsync = promisify(exec);
@ -34,7 +43,6 @@ interface PendingPermission {
timestamp: number;
}
interface ServerState {
chatHistory: ChatCompletionMessageParam[];
displayMessages: DisplayMessage[]; // Messages formatted for display with tool info
@ -89,15 +97,21 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Log configuration information
const organizationId = authState.organizationId || 'personal';
const organizationId = authState.organizationId || "personal";
const assistantName = config.name;
const assistantSlug = getAssistantSlug(authState.authConfig);
const modelProvider = model.provider;
const modelName = model.model;
console.log(chalk.blue(`\nConfiguration:`));
console.log(chalk.dim(` Organization: ${organizationId}`));
console.log(chalk.dim(` Assistant: ${assistantName}${assistantSlug ? ` (${assistantSlug})` : ''}`));
console.log(
chalk.dim(
` Assistant: ${assistantName}${
assistantSlug ? ` (${assistantSlug})` : ""
}`
)
);
console.log(chalk.dim(` Model: ${modelProvider}/${modelName}`));
if (options.config) {
console.log(chalk.dim(` Config file: ${options.config}`));
@ -177,31 +191,31 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state.lastActivity = Date.now();
const { requestId, approved } = req.body;
if (!state.pendingPermission) {
return res.status(400).json({ error: "No pending permission request" });
}
if (state.pendingPermission.requestId !== requestId) {
return res.status(400).json({ error: "Invalid request ID" });
}
// Remove the permission request message
const lastMsg = state.displayMessages[state.displayMessages.length - 1];
if (lastMsg && lastMsg.messageType === "tool-permission-request") {
state.displayMessages.pop();
}
// Send the permission response to the toolPermissionManager
if (approved) {
toolPermissionManager.approveRequest(requestId);
} else {
toolPermissionManager.rejectRequest(requestId);
}
// Clear pending permission state
state.pendingPermission = null;
res.json({
success: true,
approved,
@ -290,15 +304,21 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
console.log(chalk.dim("Endpoints:"));
console.log(chalk.dim(" GET /state - Get current agent state"));
console.log(
chalk.dim(" POST /message - Send a message (body: { message: string })")
chalk.dim(
" POST /message - Send a message (body: { message: string })"
)
);
console.log(
chalk.dim(" POST /permission - Approve/reject tool (body: { requestId, approved })")
chalk.dim(
" POST /permission - Approve/reject tool (body: { requestId, approved })"
)
);
console.log(
chalk.dim(" GET /diff - Get git diff against main branch")
);
console.log(chalk.dim(" POST /exit - Gracefully shut down the server"));
console.log(
chalk.dim(" POST /exit - Gracefully shut down the server")
);
console.log(
chalk.dim(
`\nServer will shut down after ${timeoutSeconds} seconds of inactivity`
@ -573,4 +593,4 @@ async function streamChatResponseWithInterruption(
// currentStreamingMessage.isStreaming = false;
}
}
}
}

View file

@ -17,9 +17,9 @@ import {
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,
executeToolCall,
getAvailableTools,
Tool,
ToolCall,

View file

@ -1,19 +0,0 @@
import {
BUILTIN_TOOLS,
executeToolCall,
extractToolCalls,
getToolsDescription,
getToolDisplayName,
type Tool,
} from "./tools/index.js";
// Re-export all tool functionality
export {
executeToolCall,
extractToolCalls,
getToolsDescription,
getToolDisplayName,
BUILTIN_TOOLS as tools,
};
export type { Tool };

View file

@ -1,9 +1,8 @@
import { jest } from "@jest/globals";
import { formatToolCall, formatToolArgument } from "./formatters.js";
import { formatToolArgument } from "./formatters.js";
import { formatToolCall } from "./index.js";
describe("formatToolCall", () => {
const originalCwd = process.cwd();
beforeEach(() => {
// Mock process.cwd to return a consistent value
jest.spyOn(process, "cwd").mockReturnValue("/Users/test/project");

View file

@ -1,25 +1,4 @@
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
@ -41,4 +20,4 @@ export function formatToolArgument(value: any): string {
// Return other values as strings
return String(value);
}
}

View file

@ -1,102 +1,76 @@
import { getToolDisplayName, getToolsDescription, extractToolCalls } from './index.js';
import { getToolDisplayName, extractToolCalls } from "./index.js";
describe('tools/index utilities', () => {
describe('getToolDisplayName', () => {
it('should return display name for known tool', () => {
describe("tools/index utilities", () => {
describe("getToolDisplayName", () => {
it("should return display name for known tool", () => {
// The actual implementation returns the first part of the displayName
const result = getToolDisplayName('read_file');
expect(result).toBe('Read');
const result = getToolDisplayName("read_file");
expect(result).toBe("Read");
});
it('should return original name for unknown tool', () => {
const result = getToolDisplayName('unknown_tool');
expect(result).toBe('unknown_tool');
it("should return original name for unknown tool", () => {
const result = getToolDisplayName("unknown_tool");
expect(result).toBe("unknown_tool");
});
it('should handle empty string', () => {
const result = getToolDisplayName('');
expect(result).toBe('');
it("should handle empty string", () => {
const result = getToolDisplayName("");
expect(result).toBe("");
});
});
describe('getToolsDescription', () => {
it('should return formatted JSON description of tools', () => {
const result = getToolsDescription();
expect(result).toContain('"name": "read_file"');
expect(result).toContain('"description": "Read the contents of a file at the specified path"');
expect(result).toContain('"type": "string"');
expect(result).toContain('"required": true');
expect(result).toContain('"required": [');
});
it('should include parameters for tools', () => {
const result = getToolsDescription();
expect(result).toContain('"filepath"');
expect(result).toContain('"content"');
expect(result).toContain('"dirpath"');
});
it('should format as valid JSON structure', () => {
const result = getToolsDescription();
// Check that it contains JSON-like structure
expect(result).toMatch(/\{\s*"name":/);
expect(result).toMatch(/"parameters":\s*\{/);
expect(result).toMatch(/"properties":\s*\{/);
});
});
describe('extractToolCalls', () => {
it('should extract single tool call', () => {
describe("extractToolCalls", () => {
it("should extract single tool call", () => {
const response = `Here's the result:
<tool>{"name": "read_file", "arguments": {"filepath": "/path/to/file.txt"}}</tool>
Done.`;
const result = extractToolCalls(response);
expect(result).toEqual([
{
name: 'read_file',
arguments: { filepath: '/path/to/file.txt' }
}
name: "read_file",
arguments: { filepath: "/path/to/file.txt" },
},
]);
});
it('should extract multiple tool calls', () => {
it("should extract multiple tool calls", () => {
const response = `First call:
<tool>{"name": "read_file", "arguments": {"filepath": "/file1.txt"}}</tool>
Second call:
<tool>{"name": "write_file", "arguments": {"filepath": "/file2.txt", "content": "hello"}}</tool>
Done.`;
const result = extractToolCalls(response);
expect(result).toEqual([
{
name: 'read_file',
arguments: { filepath: '/file1.txt' }
name: "read_file",
arguments: { filepath: "/file1.txt" },
},
{
name: 'write_file',
arguments: { filepath: '/file2.txt', content: 'hello' }
}
name: "write_file",
arguments: { filepath: "/file2.txt", content: "hello" },
},
]);
});
it('should handle tool calls with complex arguments', () => {
it("should handle tool calls with complex arguments", () => {
const response = `<tool>{"name": "search_code", "arguments": {"pattern": "function.*test", "path": "/src", "options": {"recursive": true, "ignoreCase": false}}}</tool>`;
const result = extractToolCalls(response);
expect(result).toEqual([
{
name: 'search_code',
arguments: {
pattern: 'function.*test',
path: '/src',
options: { recursive: true, ignoreCase: false }
}
}
name: "search_code",
arguments: {
pattern: "function.*test",
path: "/src",
options: { recursive: true, ignoreCase: false },
},
},
]);
});
it('should handle multiline tool calls', () => {
it("should handle multiline tool calls", () => {
const response = `<tool>{
"name": "write_file",
"arguments": {
@ -104,110 +78,110 @@ Done.`;
"content": "Line 1\\nLine 2\\nLine 3"
}
}</tool>`;
const result = extractToolCalls(response);
expect(result).toEqual([
{
name: 'write_file',
arguments: {
filepath: '/path/to/file.txt',
content: 'Line 1\nLine 2\nLine 3'
}
}
name: "write_file",
arguments: {
filepath: "/path/to/file.txt",
content: "Line 1\nLine 2\nLine 3",
},
},
]);
});
it('should return empty array when no tool calls found', () => {
it("should return empty array when no tool calls found", () => {
const response = `This is just regular text with no tool calls.`;
const result = extractToolCalls(response);
expect(result).toEqual([]);
});
it('should handle empty response', () => {
const response = '';
it("should handle empty response", () => {
const response = "";
const result = extractToolCalls(response);
expect(result).toEqual([]);
});
it('should ignore malformed tool calls', () => {
it("should ignore malformed tool calls", () => {
// Capture console.error to avoid polluting test output
const originalConsoleError = console.error;
console.error = () => {};
const response = `Good call:
<tool>{"name": "read_file", "arguments": {"filepath": "/file.txt"}}</tool>
Bad call:
<tool>{"name": "invalid_json", "arguments": {malformed json}}</tool>
Another good call:
<tool>{"name": "write_file", "arguments": {"filepath": "/file2.txt", "content": "test"}}</tool>`;
const result = extractToolCalls(response);
expect(result).toEqual([
{
name: 'read_file',
arguments: { filepath: '/file.txt' }
name: "read_file",
arguments: { filepath: "/file.txt" },
},
{
name: 'write_file',
arguments: { filepath: '/file2.txt', content: 'test' }
}
name: "write_file",
arguments: { filepath: "/file2.txt", content: "test" },
},
]);
// Restore console.error
console.error = originalConsoleError;
});
it('should ignore tool calls missing required fields', () => {
it("should ignore tool calls missing required fields", () => {
const response = `Missing name:
<tool>{"arguments": {"filepath": "/file.txt"}}</tool>
Missing arguments:
<tool>{"name": "read_file"}</tool>
Valid call:
<tool>{"name": "read_file", "arguments": {"filepath": "/file.txt"}}</tool>`;
const result = extractToolCalls(response);
expect(result).toEqual([
{
name: 'read_file',
arguments: { filepath: '/file.txt' }
}
name: "read_file",
arguments: { filepath: "/file.txt" },
},
]);
});
it('should handle tool calls with empty arguments', () => {
it("should handle tool calls with empty arguments", () => {
const response = `<tool>{"name": "list_files", "arguments": {}}</tool>`;
const result = extractToolCalls(response);
expect(result).toEqual([
{
name: 'list_files',
arguments: {}
}
name: "list_files",
arguments: {},
},
]);
});
it('should handle tool calls with null arguments', () => {
it("should handle tool calls with null arguments", () => {
const response = `<tool>{"name": "exit", "arguments": null}</tool>`;
const result = extractToolCalls(response);
expect(result).toEqual([]);
});
it('should handle nested tool tags', () => {
it("should handle nested tool tags", () => {
const response = `<tool>{"name": "write_file", "arguments": {"filepath": "/file.txt", "content": "Some content with <tool> tags inside"}}</tool>`;
const result = extractToolCalls(response);
expect(result).toEqual([
{
name: 'write_file',
arguments: {
filepath: '/file.txt',
content: 'Some content with <tool> tags inside'
}
}
name: "write_file",
arguments: {
filepath: "/file.txt",
content: "Some content with <tool> tags inside",
},
},
]);
});
});
});
});

View file

@ -4,6 +4,7 @@ import telemetryService from "../telemetry/telemetryService.js";
import logger from "../util/logger.js";
import { exitTool } from "./exit.js";
import { fetchTool } from "./fetch.js";
import { formatToolArgument } from "./formatters.js";
import { listFilesTool } from "./listFiles.js";
import { readFileTool } from "./readFile.js";
import { runTerminalCommandTool } from "./runTerminalCommand.js";
@ -50,32 +51,6 @@ export function getToolDisplayName(toolName: string): string {
return tool?.displayName || toolName;
}
export function getToolsDescription(): string {
return BUILTIN_TOOLS.map((tool) => {
const params = Object.entries(tool.parameters)
.map(
([name, param]) =>
` "${name}": { "type": "${param.type}", "description": "${param.description}", "required": ${param.required} }`
)
.join(",\n");
return `{
"name": "${tool.name}",
"description": "${tool.description}",
"parameters": {
"type": "object",
"properties": {
${params}
},
"required": [${Object.entries(tool.parameters)
.filter(([_, param]) => param.required)
.map(([name]) => `"${name}"`)
.join(", ")}]
}
}`;
}).join(",\n");
}
export function extractToolCalls(
response: string
): Array<{ name: string; arguments: Record<string, any> }> {
@ -153,20 +128,6 @@ export async function getAvailableTools() {
return allTools;
}
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)
) {
throw new Error(
`Required parameter "${paramName}" missing for tool "${toolCall.name}"`
);
}
}
}
export async function executeToolCall(
toolCall: PreprocessedToolCall
): Promise<string> {
@ -218,3 +179,37 @@ export async function executeToolCall(
return `Error executing tool "${toolCall.name}": ${errorMessage}`;
}
}
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)
) {
throw new Error(
`Required parameter "${paramName}" missing for tool "${toolCall.name}"`
);
}
}
}
/**
* 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})`;
}

View file

@ -22,8 +22,8 @@ export const listFilesTool: Tool = {
preview: [
{
type: "text",
content: args.directory
? `Will list files in: ${formatToolArgument(args.directory)}`
content: args.dirPath
? `Will list files in: ${formatToolArgument(args.dirPath)}`
: "Will list files in current directory",
},
],

View file

@ -0,0 +1,472 @@
import { vi, describe, it, expect, beforeEach } from "vitest";
// Mock fs module
vi.mock("fs", async () => {
// Use actual fs implementation for non-mocked functions
const actualFs = await vi.importActual("fs");
return {
...(actualFs as any),
existsSync: vi.fn(),
readFileSync: vi.fn(),
};
});
// Mock telemetry service
vi.mock("./src/telemetry/telemetryService.js"); // Mock diff module
vi.mock("diff", () => ({
createTwoFilesPatch: vi.fn(),
}));
// Define mocks after vi.mock calls
const mockExistsSync = vi.mocked(await import("fs")).existsSync;
const mockReadFileSync = vi.mocked(await import("fs")).readFileSync;
const { createTwoFilesPatch: mockCreateTwoFilesPatch } = vi.mocked(
await import("diff")
);
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 { viewDiffTool } from "./viewDiff.js";
import { writeFileTool } from "./writeFile.js";
describe("Tool preprocess functions", () => {
beforeEach(() => {
vi.clearAllMocks();
// Reset fs mock defaults
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("existing file content");
// Reset diff mock
vi.mocked(mockCreateTwoFilesPatch).mockImplementation(
() => "mock diff content"
);
});
describe("fetchTool.preprocess", () => {
it("should return preview with URL to fetch", async () => {
const args = { url: "https://example.com" };
const result = await fetchTool.preprocess!(args);
expect(result).toEqual({
preview: [
{
type: "text",
content: "Will fetch: https://example.com",
},
],
args,
});
});
it("should handle URL with timeout parameter", async () => {
const args = { url: "https://example.com", timeout: 5000 };
const result = await fetchTool.preprocess!(args);
expect(result).toEqual({
preview: [
{
type: "text",
content: "Will fetch: https://example.com",
},
],
args,
});
});
});
describe("listFilesTool.preprocess", () => {
it("should return preview with directory path when directory arg present", async () => {
const args = { dirPath: "some/path" };
const result = await listFilesTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "Will list files in: some/path",
},
],
});
});
it("should show current directory when no directory arg", async () => {
const args = {};
const result = await listFilesTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "Will list files in current directory",
},
],
});
});
});
describe("readFileTool.preprocess", () => {
it("should return formatted tool call preview", async () => {
const args = { filepath: "path/to/file.txt" };
const result = await readFileTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "Will read path/to/file.txt",
},
],
});
});
});
describe("runTerminalCommandTool.preprocess", () => {
it("should return preview with full command when short", async () => {
const args = { command: "ls -la" };
const result = await runTerminalCommandTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "Will run: ls -la",
},
],
});
});
it("should truncate long commands", async () => {
const longCommand = "a".repeat(100);
const args = { command: longCommand };
const result = await runTerminalCommandTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: `Will run: ${"a".repeat(60)}...`,
},
],
});
});
});
describe("searchCodeTool.preprocess", () => {
it("should return preview with full pattern when short", async () => {
const args = { pattern: "searchTerm" };
const result = await searchCodeTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: 'Will search for: "searchTerm"',
},
],
});
});
it("should truncate long patterns", async () => {
const longPattern = "a".repeat(100);
const args = { pattern: longPattern };
const result = await searchCodeTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: `Will search for: "${"a".repeat(50)}..."`,
},
],
});
});
});
describe("viewDiffTool.preprocess", () => {
it("should return preview indicating git diff will be shown", async () => {
const args = { path: "/repo/path" };
const result = await viewDiffTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "Will show git diff",
},
],
});
});
it("should handle empty args", async () => {
const args = {};
const result = await viewDiffTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "Will show git diff",
},
],
});
});
});
describe("writeFileTool.preprocess", () => {
it("should show diff preview when file exists", async () => {
// Setup mocks for this test
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("old content");
const args = { filepath: "path/to/file.txt", content: "new content" };
const result = await writeFileTool.preprocess!(args);
expect(mockExistsSync).toHaveBeenCalled();
expect(mockReadFileSync).toHaveBeenCalled();
expect(mockCreateTwoFilesPatch).toHaveBeenCalled();
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "Preview of changes:",
},
{
type: "diff",
content: "mock diff content",
},
],
});
});
it("should show new file content preview when file doesn't exist", async () => {
mockExistsSync.mockReturnValue(false);
const args = {
filepath: "path/to/file.txt",
content: "line 1\nline 2\nline 3\nline 4",
};
const result = await writeFileTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "New file content:",
},
{
type: "text",
content: "line 1",
paddingLeft: 2,
},
{
type: "text",
content: "line 2",
paddingLeft: 2,
},
{
type: "text",
content: "line 3",
paddingLeft: 2,
},
{
type: "text",
content: "... (1 more lines)",
},
],
});
});
it("should handle empty lines in new file preview", async () => {
mockExistsSync.mockReturnValue(false);
const args = {
filepath: "path/to/file.txt",
content: "line 1\n\nline 3",
};
const result = await writeFileTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "New file content:",
},
{
type: "text",
content: "line 1",
paddingLeft: 2,
},
{
type: "text",
content: " ",
paddingLeft: 2,
},
{
type: "text",
content: "line 3",
paddingLeft: 2,
},
],
});
});
it("should handle fs errors gracefully", async () => {
mockExistsSync.mockImplementation(() => {
throw new Error("Permission denied");
});
const args = { filepath: "path/to/file.txt", content: "new content" };
const result = await writeFileTool.preprocess!(args);
expect(result).toEqual({
args,
preview: [
{
type: "text",
content: "New file content:",
},
{
type: "text",
content: "new content",
paddingLeft: 2,
},
],
});
});
});
describe("searchAndReplaceInFileTool.preprocess", () => {
it("should process simple search and replace", async () => {
// Setup mocks
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("old line 1\nold line 2\nold line 3");
const args = {
filepath: "path/to/file.txt",
diffs: [
`------- SEARCH
old line 2
=======
new line 2
+++++++ REPLACE`,
],
};
const result = await searchAndReplaceInFileTool.preprocess!(args);
expect(mockExistsSync).toHaveBeenCalled();
expect(mockReadFileSync).toHaveBeenCalled();
expect(mockCreateTwoFilesPatch).toHaveBeenCalled();
expect(result.args).toEqual({
filepath: expect.any(String),
newContent: "old line 1\nnew line 2\nold line 3",
oldContent: "old line 1\nold line 2\nold line 3",
});
expect(result.preview).toEqual([
{
type: "text",
content: "Will make the following changes:",
},
{
type: "diff",
content: "mock diff content",
},
]);
});
it("should throw error when file doesn't exist", async () => {
mockExistsSync.mockReturnValue(false);
const args = {
filepath: "/nonexistent/file.txt",
diffs: ["some diff"],
};
await expect(
searchAndReplaceInFileTool.preprocess!(args)
).rejects.toThrowError(/file .* does not exist/);
});
it("should throw error when no search/replace blocks found", async () => {
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("file content");
const args = {
filepath: "path/to/file.txt",
diffs: ["invalid diff format"],
};
await expect(
searchAndReplaceInFileTool.preprocess!(args)
).rejects.toThrowError(
"No complete search/replace blocks found in any diffs"
);
});
it("should throw error when search content not found", async () => {
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("old line 1\nold line 2\nold line 3");
const args = {
filepath: "path/to/file.txt",
diffs: [
`------- SEARCH
nonexistent content
=======
replacement
+++++++ REPLACE`,
],
};
await expect(
searchAndReplaceInFileTool.preprocess!(args)
).rejects.toThrowError(/Search content not found in block 1:/);
});
it("should process multiple search/replace blocks", async () => {
mockExistsSync.mockReturnValue(true);
mockReadFileSync.mockReturnValue("line 1\nline 2\nline 3\nline 4");
const args = {
filepath: "path/to/file.txt",
diffs: [
`------- SEARCH
line 1
=======
modified line 1
+++++++ REPLACE
------- SEARCH
line 3
=======
modified line 3
+++++++ REPLACE`,
],
};
const result = await searchAndReplaceInFileTool.preprocess!(args);
expect(result.args.newContent).toBe(
"modified line 1\nline 2\nmodified line 3\nline 4"
);
});
});
});

View file

@ -1,6 +1,6 @@
import * as fs from "fs";
import { Tool } from "./types.js";
import { formatToolCall } from "./formatters.js";
import { formatToolArgument } from "./formatters.js";
export const readFileTool: Tool = {
name: "read_file",
@ -17,7 +17,12 @@ export const readFileTool: Tool = {
preprocess: async (args) => {
return {
args,
preview: [{ type: "text", content: formatToolCall("read_file", args) }],
preview: [
{
type: "text",
content: `Will read ${formatToolArgument(args.filepath)}`,
},
],
};
},
run: async (args: { filepath: string }): Promise<string> => {

View file

@ -1,8 +1,8 @@
import { Box, Text } from "ink";
import path from "path";
import React from "react";
import { getToolDisplayName } from "../tools.js";
import { ColoredDiff } from "./ColoredDiff.js";
import { getToolDisplayName } from "../tools/index.js";
interface ToolResultSummaryProps {
toolName?: string;

View file

@ -1,6 +1,6 @@
import { Box, Text, useInput } from "ink";
import React, { useState } from "react";
import { formatToolCall } from "../../tools/formatters.js";
import { formatToolCall } from "../../tools/index.js";
import { ToolPreview } from "./ToolPreview.js";
import { ToolCallPreview } from "../../tools/types.js";

View file

@ -1,8 +1,8 @@
import { Box, Text } from "ink";
import React from "react";
import { getToolDisplayName } from "../../tools.js";
import { ColoredDiff } from "../ColoredDiff.js";
import { ToolCallPreview } from "../../tools/types.js";
import { getToolDisplayName } from "../../tools/index.js";
interface ToolPreviewProps {
toolCallPreview?: ToolCallPreview[];

View file

@ -11,7 +11,6 @@ import {
streamChatResponse,
} from "../../streamChatResponse.js";
import telemetryService from "../../telemetry/telemetryService.js";
import { formatToolCall } from "../../tools/formatters.js";
import { formatError } from "../../util/formatError.js";
import logger from "../../util/logger.js";
@ -19,6 +18,7 @@ import { initializeChatHistory } from "../../commands/chat.js";
import { posthogService } from "../../telemetry/posthogService.js";
import { DisplayMessage } from "../types.js";
import { ToolCallPreview } from "../../tools/types.js";
import { formatToolCall } from "../../tools/index.js";
interface UseChatProps {
assistant?: AssistantUnrolled;

10
vitest.config.ts Normal file
View file

@ -0,0 +1,10 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['**/*.vitest.ts'],
exclude: ['**/node_modules/**', '**/dist/**'],
globals: true,
environment: 'node',
},
});