From f69ba1767898dd7226243a9bcce76acd87fb60a3 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 15:57:40 -0700 Subject: [PATCH] fix: SystemMessageService so that system message updates with mode changes --- extensions/cli/src/commands/chat.ts | 18 +- extensions/cli/src/messageConversion.ts | 24 +++ .../src/services/SystemMessageService.test.ts | 187 ++++++++++++++++++ .../cli/src/services/SystemMessageService.ts | 106 ++++++++++ extensions/cli/src/services/index.ts | 14 ++ extensions/cli/src/services/types.ts | 1 + extensions/cli/src/slashCommands.info.test.ts | 27 +-- extensions/cli/src/slashCommands.test.ts | 19 ++ extensions/cli/src/streamChatResponse.test.ts | 2 +- extensions/cli/src/streamChatResponse.ts | 11 +- extensions/cli/src/systemMessage.test.ts | 14 +- extensions/cli/src/tools/formatters.test.ts | 160 ++++++++++----- extensions/cli/src/tools/index.test.ts | 2 +- .../cli/src/tools/{index.ts => index.tsx} | 16 +- extensions/cli/src/ui/ToolResultSummary.tsx | 2 +- .../cli/src/ui/components/MemoizedMessage.tsx | 3 +- .../cli/src/ui/hooks/useChat.helpers.ts | 12 +- extensions/cli/vitest.config.ts | 5 + 18 files changed, 525 insertions(+), 98 deletions(-) create mode 100644 extensions/cli/src/services/SystemMessageService.test.ts create mode 100644 extensions/cli/src/services/SystemMessageService.ts rename extensions/cli/src/tools/{index.ts => index.tsx} (94%) diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index bbc417c05..44ebc9cff 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -4,7 +4,6 @@ import type { ChatHistoryItem, Session } from "core/index.js"; import { ChatDescriber } from "core/util/chatDescriber.js"; import * as readlineSync from "readline-sync"; -import { getDisplayableAsciiArt } from "../asciiArt.js"; import { compactChatHistory, findCompactionIndex, @@ -24,7 +23,6 @@ import { updateSessionTitle, } from "../session.js"; import { streamChatResponse } from "../streamChatResponse.js"; -import { constructSystemMessage } from "../systemMessage.js"; import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { startTUIChat } from "../ui/index.js"; @@ -102,21 +100,7 @@ export async function initializeChatHistory( } } - // If no session loaded or not resuming, initialize with system message - const chatHistory: ChatHistoryItem[] = []; - const systemMessage = await constructSystemMessage( - options.rule, - options.format, - options.headless, - ); - if (systemMessage) { - chatHistory.push({ - message: { role: "system", content: systemMessage }, - contextItems: [], - }); - } - - return chatHistory; + return []; } // Helper function to handle manual compaction diff --git a/extensions/cli/src/messageConversion.ts b/extensions/cli/src/messageConversion.ts index fbe6eb065..d182f5425 100644 --- a/extensions/cli/src/messageConversion.ts +++ b/extensions/cli/src/messageConversion.ts @@ -341,6 +341,30 @@ export function convertFromUnifiedHistory( return messages; } +/** + * Convert ChatHistoryItem array to ChatCompletionMessageParam array with injected system message + * @param historyItems - The chat history items + * @param systemMessage - The system message to inject at the beginning + */ +export function convertFromUnifiedHistoryWithSystemMessage( + historyItems: ChatHistoryItem[], + systemMessage: string, +): ChatCompletionMessageParam[] { + const messages: ChatCompletionMessageParam[] = []; + + // Inject system message at the beginning + messages.push({ + role: "system", + content: systemMessage, + }); + + // Convert the rest of the history + const convertedMessages = convertFromUnifiedHistory(historyItems); + messages.push(...convertedMessages); + + return messages; +} + /** * Extract tool call information from a ChatHistoryItem */ diff --git a/extensions/cli/src/services/SystemMessageService.test.ts b/extensions/cli/src/services/SystemMessageService.test.ts new file mode 100644 index 000000000..a17894ee9 --- /dev/null +++ b/extensions/cli/src/services/SystemMessageService.test.ts @@ -0,0 +1,187 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { modeService } from "./ModeService.js"; +import { SystemMessageService } from "./SystemMessageService.js"; + +// Mock the systemMessage module +vi.mock("../systemMessage.js", () => ({ + constructSystemMessage: vi.fn(), +})); + +// Mock the logger +vi.mock("../util/logger.js", () => ({ + logger: { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); + +describe("SystemMessageService", () => { + let service: SystemMessageService; + let constructSystemMessageMock: any; + + beforeEach(async () => { + // Reset mocks + vi.clearAllMocks(); + + // Get mock reference + const { constructSystemMessage } = await import("../systemMessage.js"); + constructSystemMessageMock = constructSystemMessage as any; + + // Create new service instance + service = new SystemMessageService(); + }); + + afterEach(async () => { + await service.cleanup(); + }); + + describe("initialization", () => { + it("should initialize with provided configuration", async () => { + const config = { + additionalRules: ["rule1", "rule2"], + format: "json" as const, + headless: true, + }; + + const state = await service.initialize(config); + + expect(state).toEqual(config); + expect(service.isReady()).toBe(true); + }); + + it("should initialize with empty configuration", async () => { + const state = await service.initialize({}); + + expect(state).toEqual({}); + expect(service.isReady()).toBe(true); + }); + }); + + describe("getSystemMessage", () => { + it("should call constructSystemMessage with current configuration and mode", async () => { + const config = { + additionalRules: ["rule1"], + format: "json" as const, + headless: true, + }; + + constructSystemMessageMock.mockResolvedValue("Test system message"); + + await service.initialize(config); + const message = await service.getSystemMessage(); + + expect(constructSystemMessageMock).toHaveBeenCalledWith( + ["rule1"], + "json", + true, + "normal", // Default mode + ); + expect(message).toBe("Test system message"); + }); + + it("should use updated mode when mode changes", async () => { + constructSystemMessageMock.mockResolvedValue("Updated system message"); + + await service.initialize({}); + + // Simulate mode change + modeService.emit("modeChanged", "plan", "normal"); + + const message = await service.getSystemMessage(); + + expect(constructSystemMessageMock).toHaveBeenCalledWith( + undefined, + undefined, + undefined, + "plan", + ); + expect(message).toBe("Updated system message"); + }); + }); + + describe("updateConfig", () => { + it("should update configuration partially", async () => { + await service.initialize({ + additionalRules: ["rule1"], + headless: false, + }); + + service.updateConfig({ + format: "json", + }); + + constructSystemMessageMock.mockResolvedValue("Updated message"); + await service.getSystemMessage(); + + expect(constructSystemMessageMock).toHaveBeenCalledWith( + ["rule1"], + "json", + false, + "normal", + ); + }); + + it("should override existing configuration", async () => { + await service.initialize({ + additionalRules: ["rule1"], + format: "json" as const, + }); + + service.updateConfig({ + additionalRules: ["rule2", "rule3"], + }); + + constructSystemMessageMock.mockResolvedValue("Updated message"); + await service.getSystemMessage(); + + expect(constructSystemMessageMock).toHaveBeenCalledWith( + ["rule2", "rule3"], + "json", + undefined, + "normal", + ); + }); + }); + + describe("mode tracking", () => { + it("should track current mode from ModeService", async () => { + await service.initialize({}); + + expect(service.getCurrentMode()).toBe("normal"); + + // Simulate mode change + modeService.emit("modeChanged", "auto", "normal"); + + expect(service.getCurrentMode()).toBe("auto"); + }); + + it("should initialize with current mode from ModeService", async () => { + // Mock modeService.getCurrentMode + vi.spyOn(modeService, "getCurrentMode").mockReturnValue("plan"); + + const newService = new SystemMessageService(); + await newService.initialize({}); + + expect(newService.getCurrentMode()).toBe("plan"); + + await newService.cleanup(); + }); + }); + + describe("error handling", () => { + it("should handle constructSystemMessage errors gracefully", async () => { + constructSystemMessageMock.mockRejectedValue( + new Error("Failed to construct"), + ); + + await service.initialize({}); + + await expect(service.getSystemMessage()).rejects.toThrow( + "Failed to construct", + ); + }); + }); +}); diff --git a/extensions/cli/src/services/SystemMessageService.ts b/extensions/cli/src/services/SystemMessageService.ts new file mode 100644 index 000000000..2711f6990 --- /dev/null +++ b/extensions/cli/src/services/SystemMessageService.ts @@ -0,0 +1,106 @@ +import { PermissionMode } from "../permissions/types.js"; +import { constructSystemMessage } from "../systemMessage.js"; +import { logger } from "../util/logger.js"; + +import { BaseService } from "./BaseService.js"; +import { modeService } from "./ModeService.js"; + +export interface SystemMessageServiceState { + additionalRules?: string[]; + format?: "json"; + headless?: boolean; +} + +/** + * Service for managing dynamic system message construction + * Provides fresh system messages that reflect current mode and configuration + */ +export class SystemMessageService extends BaseService { + private currentMode: PermissionMode = "normal"; + + constructor() { + super("SystemMessageService", {}); + + // Listen to mode changes from ModeService + this.setupModeListener(); + } + + /** + * Set up listener for mode changes + */ + private setupModeListener(): void { + modeService.on("modeChanged", (newMode: PermissionMode) => { + logger.debug(`SystemMessageService: Mode changed to ${newMode}`); + this.currentMode = newMode; + }); + + // Initialize current mode + this.currentMode = modeService.getCurrentMode(); + } + + /** + * Initialize the service + */ + async doInitialize(args: { + additionalRules?: string[]; + format?: "json"; + headless?: boolean; + }): Promise { + this.setState({ + additionalRules: args.additionalRules, + format: args.format, + headless: args.headless, + }); + + logger.debug("SystemMessageService initialized", { + hasAdditionalRules: !!args.additionalRules?.length, + format: args.format, + headless: args.headless, + }); + + return this.currentState; + } + + /** + * Get a fresh system message with current mode and configuration + */ + public async getSystemMessage(): Promise { + const { additionalRules, format, headless } = this.currentState; + + const systemMessage = await constructSystemMessage( + additionalRules, + format, + headless, + this.currentMode, + ); + + logger.debug("Generated fresh system message", { + mode: this.currentMode, + messageLength: systemMessage.length, + }); + + return systemMessage; + } + + /** + * Update configuration that affects system message + */ + public updateConfig(config: Partial): void { + this.setState({ + ...this.currentState, + ...config, + }); + + logger.debug("SystemMessageService config updated", config); + } + + /** + * Get the current mode being used for system messages + */ + public getCurrentMode(): PermissionMode { + return this.currentMode; + } +} + +// Export singleton instance +export const systemMessageService = new SystemMessageService(); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index 81b1e7318..0f9bc65cc 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -11,6 +11,7 @@ import { ModelService } from "./ModelService.js"; import { modeService } from "./ModeService.js"; import { ResourceMonitoringService } from "./ResourceMonitoringService.js"; import { serviceContainer } from "./ServiceContainer.js"; +import { systemMessageService } from "./SystemMessageService.js"; import { ApiClientServiceState, AuthServiceState, @@ -111,6 +112,18 @@ export async function initializeServices( toolPermissionState, ); + // Initialize SystemMessageService with command options + serviceContainer.register( + SERVICE_NAMES.SYSTEM_MESSAGE, + () => + systemMessageService.initialize({ + additionalRules: commandOptions.rule, + format: undefined, // format is not part of BaseCommandOptions + headless: initOptions.headless, + }), + [], // No dependencies + ); + serviceContainer.register( SERVICE_NAMES.AUTH, () => authService.initialize(), @@ -293,6 +306,7 @@ export const services = { fileIndex: fileIndexService, mode: modeService, resourceMonitoring: resourceMonitoringService, + systemMessage: systemMessageService, } as const; // Export the service container for advanced usage diff --git a/extensions/cli/src/services/types.ts b/extensions/cli/src/services/types.ts index 112611eff..75470d958 100644 --- a/extensions/cli/src/services/types.ts +++ b/extensions/cli/src/services/types.ts @@ -106,6 +106,7 @@ export const SERVICE_NAMES = { TOOL_PERMISSIONS: "toolPermissions", FILE_INDEX: "fileIndex", RESOURCE_MONITORING: "resourceMonitoring", + SYSTEM_MESSAGE: "systemMessage", } as const; /** diff --git a/extensions/cli/src/slashCommands.info.test.ts b/extensions/cli/src/slashCommands.info.test.ts index e332ad15c..637edcf92 100644 --- a/extensions/cli/src/slashCommands.info.test.ts +++ b/extensions/cli/src/slashCommands.info.test.ts @@ -1,10 +1,11 @@ import { describe, it, expect, vi, beforeEach } from "vitest"; -import { handleSlashCommands } from "./slashCommands.js"; -import { services } from "./services/index.js"; + import * as workosModule from "./auth/workos.js"; -import * as versionModule from "./version.js"; +import { services } from "./services/index.js"; import * as sessionModule from "./session.js"; +import { handleSlashCommands } from "./slashCommands.js"; import { posthogService } from "./telemetry/posthogService.js"; +import * as versionModule from "./version.js"; // Mock all dependencies vi.mock("./auth/workos.js"); @@ -39,7 +40,7 @@ describe("handleSlashCommands - /info", () => { vi.spyOn(process, "cwd").mockReturnValue("/test/working/directory"); // Mock posthog - vi.mocked(posthogService.capture).mockReturnValue(undefined); + vi.mocked(posthogService.capture).mockReturnValue(Promise.resolve()); // Mock version vi.mocked(versionModule.getVersion).mockReturnValue("1.2.3"); @@ -56,7 +57,7 @@ describe("handleSlashCommands - /info", () => { // Mock config service const mockConfigState = { - config: { name: "test-config" }, + config: { name: "test-config", version: "1.0.0" } as any, configPath: "/test/config.yaml", }; vi.mocked(services.config.getState).mockReturnValue(mockConfigState); @@ -65,7 +66,7 @@ describe("handleSlashCommands - /info", () => { name: "gpt-4", }); - const result = await handleSlashCommands("/info", mockAssistant); + const result = await handleSlashCommands("/info", mockAssistant as any); expect(result).toBeDefined(); expect(result?.output).toContain("CLI Information:"); @@ -74,7 +75,7 @@ describe("handleSlashCommands - /info", () => { "Working Directory: /test/working/directory", ); expect(result?.output).toContain("Configuration:"); - expect(result?.output).toContain("Model: openai/gpt-4"); + expect(result?.output).toContain("Model: gpt-4"); expect(result?.exit).toBe(false); }); @@ -89,7 +90,7 @@ describe("handleSlashCommands - /info", () => { // Mock config service const mockConfigState = { - config: { name: "test-config" }, + config: { name: "test-config", version: "1.0.0" } as any, configPath: "/test/config.yaml", }; vi.mocked(services.config.getState).mockReturnValue(mockConfigState); @@ -98,11 +99,11 @@ describe("handleSlashCommands - /info", () => { name: "claude-3-sonnet", }); - const result = await handleSlashCommands("/info", mockAssistant); + const result = await handleSlashCommands("/info", mockAssistant as any); expect(result?.output).toContain("Authentication:"); expect(result?.output).toContain("Email: test@example.com"); - expect(result?.output).toContain("Model: anthropic/claude-3-sonnet"); + expect(result?.output).toContain("Model: claude-3-sonnet"); }); it("should handle missing model info gracefully", async () => { @@ -111,13 +112,13 @@ describe("handleSlashCommands - /info", () => { // Mock config service with no model info const mockConfigState = { - config: { name: "test-config" }, + config: { name: "test-config", version: "1.0.0" } as any, configPath: "/test/config.yaml", }; vi.mocked(services.config.getState).mockReturnValue(mockConfigState); vi.mocked(services.model.getModelInfo).mockReturnValue(null); - const result = await handleSlashCommands("/info", mockAssistant); + const result = await handleSlashCommands("/info", mockAssistant as any); expect(result?.output).toContain("Model: Not available"); }); @@ -131,7 +132,7 @@ describe("handleSlashCommands - /info", () => { throw new Error("Service not available"); }); - const result = await handleSlashCommands("/info", mockAssistant); + const result = await handleSlashCommands("/info", mockAssistant as any); expect(result?.output).toContain("Configuration service not available"); }); diff --git a/extensions/cli/src/slashCommands.test.ts b/extensions/cli/src/slashCommands.test.ts index 50185cf33..d8e1512ef 100644 --- a/extensions/cli/src/slashCommands.test.ts +++ b/extensions/cli/src/slashCommands.test.ts @@ -44,11 +44,30 @@ vi.mock("./commands/commands.js", () => ({ getAllSlashCommands: vi.fn(() => []), })); +// Mock logger to avoid file system operations +vi.mock("./util/logger.js", () => ({ + logger: { + debug: vi.fn(), + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }, +})); + +// Mock env.js to avoid file operations +vi.mock("./env.js", () => ({ + env: { + continueHome: "/home/test/.continue", + appUrl: "https://hub.continue.dev", + }, +})); + // Mock os and path vi.mock("os", () => ({ default: { homedir: vi.fn(() => "/home/test"), }, + homedir: vi.fn(() => "/home/test"), })); vi.mock("path", () => ({ diff --git a/extensions/cli/src/streamChatResponse.test.ts b/extensions/cli/src/streamChatResponse.test.ts index 52b6515ad..56fb42a23 100644 --- a/extensions/cli/src/streamChatResponse.test.ts +++ b/extensions/cli/src/streamChatResponse.test.ts @@ -6,8 +6,8 @@ import { vi } from "vitest"; import { toolPermissionManager } from "./permissions/permissionManager.js"; import { - preprocessStreamedToolCalls, executeStreamedToolCalls, + preprocessStreamedToolCalls, } from "./streamChatResponse.helpers.js"; import { processStreamingResponse } from "./streamChatResponse.js"; import { ToolCall } from "./tools/index.js"; diff --git a/extensions/cli/src/streamChatResponse.ts b/extensions/cli/src/streamChatResponse.ts index f481bb802..290c3bb07 100644 --- a/extensions/cli/src/streamChatResponse.ts +++ b/extensions/cli/src/streamChatResponse.ts @@ -6,7 +6,7 @@ import * as dotenv from "dotenv"; import type { ChatCompletionTool } from "openai/resources.mjs"; import { - convertFromUnifiedHistory, + convertFromUnifiedHistoryWithSystemMessage, createHistoryItem, } from "./messageConversion.js"; import { filterExcludedTools } from "./permissions/index.js"; @@ -16,6 +16,7 @@ import { MCPTool, SERVICE_NAMES, } from "./services/index.js"; +import { systemMessageService } from "./services/SystemMessageService.js"; import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; import { @@ -355,7 +356,13 @@ export async function processStreamingResponse( isHeadless, tools, } = options; - const openaiChatHistory = convertFromUnifiedHistory(chatHistory); + + // Get fresh system message and inject it + const systemMessage = await systemMessageService.getSystemMessage(); + const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage( + chatHistory, + systemMessage, + ); const requestStartTime = Date.now(); const streamFactory = async (retryAbortSignal: AbortSignal) => { diff --git a/extensions/cli/src/systemMessage.test.ts b/extensions/cli/src/systemMessage.test.ts index 895234c9b..d77794734 100644 --- a/extensions/cli/src/systemMessage.test.ts +++ b/extensions/cli/src/systemMessage.test.ts @@ -18,6 +18,8 @@ vi.mock("./args.js", () => ({ .mockImplementation((spec: string) => Promise.resolve(spec)), })); +const PLAN_MODE_STRING = "You are operating in _Plan Mode_"; + describe("constructSystemMessage", () => { it("should return base system message with rules when additionalRules is provided", async () => { const rules = ["These are the rules for the assistant."]; @@ -167,7 +169,7 @@ Rule 3: Third rule`; ); expect(result).toContain("You are an agent in the Continue CLI"); - expect(result).toContain("PLAN MODE: You are operating in plan mode"); + expect(result).toContain(PLAN_MODE_STRING); expect(result).toContain( "which means that your goal is to help the user investigate their ideas", ); @@ -187,7 +189,7 @@ Rule 3: Third rule`; ); expect(result).toContain("You are an agent in the Continue CLI"); - expect(result).not.toContain("PLAN MODE: You are operating in plan mode"); + expect(result).not.toContain(PLAN_MODE_STRING); expect(result).not.toContain( "which means that your goal is to help the user investigate their ideas", ); @@ -197,7 +199,7 @@ Rule 3: Third rule`; const result = await constructSystemMessage(); expect(result).toContain("You are an agent in the Continue CLI"); - expect(result).not.toContain("PLAN MODE: You are operating in plan mode"); + expect(result).not.toContain(PLAN_MODE_STRING); expect(result).not.toContain( "which means that your goal is to help the user investigate their ideas", ); @@ -211,7 +213,7 @@ Rule 3: Third rule`; "plan", ); - expect(result).toContain("PLAN MODE: You are operating in plan mode"); + expect(result).toContain(PLAN_MODE_STRING); expect(result).toContain("read-only tools"); expect(result).toContain("write / delete / create files"); }); @@ -225,7 +227,7 @@ Rule 3: Third rule`; ); expect(result).toContain("IMPORTANT: You are running in headless mode"); - expect(result).toContain("PLAN MODE: You are operating in plan mode"); + expect(result).toContain(PLAN_MODE_STRING); expect(result).toContain( "which means that your goal is to help the user investigate their ideas", ); @@ -242,7 +244,7 @@ Rule 3: Third rule`; expect(result).toContain( "IMPORTANT: You are operating in JSON output mode", ); - expect(result).toContain("PLAN MODE: You are operating in plan mode"); + expect(result).toContain(PLAN_MODE_STRING); expect(result).toContain( "which means that your goal is to help the user investigate their ideas", ); diff --git a/extensions/cli/src/tools/formatters.test.ts b/extensions/cli/src/tools/formatters.test.ts index a9ca67ca9..1bef86dbd 100644 --- a/extensions/cli/src/tools/formatters.test.ts +++ b/extensions/cli/src/tools/formatters.test.ts @@ -1,4 +1,6 @@ -import { vi } from "vitest"; +import { render } from "ink-testing-library"; +import React from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { formatToolArgument } from "./formatters.js"; @@ -15,74 +17,144 @@ describe("formatToolCall", () => { }); it("should format tool name without arguments", () => { - expect(formatToolCall("Write")).toBe("Write"); - expect(formatToolCall("Read", {})).toBe("Read"); - expect(formatToolCall("non_existent_tool", null)).toBe("non_existent_tool"); + const writeResult = render( + React.createElement(() => formatToolCall("Write") as React.ReactElement), + ); + expect(writeResult.lastFrame()).toBe("Write"); + + const readResult = render( + React.createElement( + () => formatToolCall("Read", {}) as React.ReactElement, + ), + ); + expect(readResult.lastFrame()).toBe("Read"); + + const nonExistentResult = render( + React.createElement( + () => formatToolCall("non_existent_tool", null) as React.ReactElement, + ), + ); + expect(nonExistentResult.lastFrame()).toBe("non_existent_tool"); }); it("should format tool name with relative path argument", () => { - expect(formatToolCall("Write", { filepath: "README.md" })).toBe( - "Write(README.md)", + const writeResult = render( + React.createElement( + () => + formatToolCall("Write", { + filepath: "README.md", + }) as React.ReactElement, + ), ); - expect(formatToolCall("Read", { filepath: "src/index.ts" })).toBe( - "Read(src/index.ts)", + expect(writeResult.lastFrame()).toBe("Write(README.md)"); + + const readResult = render( + React.createElement( + () => + formatToolCall("Read", { + filepath: "src/index.ts", + }) as React.ReactElement, + ), ); + expect(readResult.lastFrame()).toBe("Read(src/index.ts)"); }); it("should convert absolute paths to relative paths", () => { - expect( - formatToolCall("Write", { - filepath: "/Users/test/project/README.md", - }), - ).toBe("Write(README.md)"); + const writeResult = render( + React.createElement( + () => + formatToolCall("Write", { + filepath: "/Users/test/project/README.md", + }) as React.ReactElement, + ), + ); + expect(writeResult.lastFrame()).toBe("Write(README.md)"); - expect( - formatToolCall("Read", { - filepath: "/Users/test/project/src/components/App.tsx", - }), - ).toBe("Read(src/components/App.tsx)"); + const readResult = render( + React.createElement( + () => + formatToolCall("Read", { + filepath: "/Users/test/project/src/components/App.tsx", + }) as React.ReactElement, + ), + ); + expect(readResult.lastFrame()).toBe("Read(src/components/App.tsx)"); }); it("should handle absolute paths outside the project", () => { - expect(formatToolCall("Write", { filepath: "/Users/other/file.txt" })).toBe( - "Write(../../other/file.txt)", + const result = render( + React.createElement( + () => + formatToolCall("Write", { + filepath: "/Users/other/file.txt", + }) as React.ReactElement, + ), ); + expect(result.lastFrame()).toBe("Write(../../other/file.txt)"); }); it("should handle non-path arguments", () => { - expect(formatToolCall("Search", { pattern: "TODO" })).toBe("Search(TODO)"); - expect(formatToolCall("Search", { pattern: 123 })).toBe("Search(123)"); + const stringResult = render( + React.createElement( + () => + formatToolCall("Search", { pattern: "TODO" }) as React.ReactElement, + ), + ); + expect(stringResult.lastFrame()).toBe("Search(TODO)"); + + const numberResult = render( + React.createElement( + () => formatToolCall("Search", { pattern: 123 }) as React.ReactElement, + ), + ); + expect(numberResult.lastFrame()).toBe("Search(123)"); }); it("should use first argument when multiple are provided", () => { - expect( - formatToolCall("Write", { - filepath: "test.txt", - content: "Hello world", - }), - ).toBe("Write(test.txt)"); + const result = render( + React.createElement( + () => + formatToolCall("Write", { + filepath: "test.txt", + content: "Hello world", + }) as React.ReactElement, + ), + ); + expect(result.lastFrame()).toBe("Write(test.txt)"); }); it("should handle multi-line string arguments with ellipsis", () => { - expect( - formatToolCall("Bash", { - command: "echo 'first line'\necho 'second line'\necho 'third line'", - }), - ).toBe("Bash(echo 'first line'...)"); + const bashResult = render( + React.createElement( + () => + formatToolCall("Bash", { + command: "echo 'first line'\necho 'second line'\necho 'third line'", + }) as React.ReactElement, + ), + ); + expect(bashResult.lastFrame()).toBe("Bash(echo 'first line'...)"); - expect( - formatToolCall("Edit", { - old_string: "line 1\nline 2\nline 3", - new_string: "updated content", - }), - ).toBe("Edit(line 1...)"); + const editResult = render( + React.createElement( + () => + formatToolCall("Edit", { + old_string: "line 1\nline 2\nline 3", + new_string: "updated content", + }) as React.ReactElement, + ), + ); + expect(editResult.lastFrame()).toBe("Edit(line 1...)"); // Test with empty first line - expect( - formatToolCall("Write", { - content: "\nSecond line\nThird line", - }), - ).toBe("Write(...)"); + const writeResult = render( + React.createElement( + () => + formatToolCall("Write", { + content: "\nSecond line\nThird line", + }) as React.ReactElement, + ), + ); + expect(writeResult.lastFrame()).toBe("Write(...)"); }); }); diff --git a/extensions/cli/src/tools/index.test.ts b/extensions/cli/src/tools/index.test.ts index 38279d8da..9e1940812 100644 --- a/extensions/cli/src/tools/index.test.ts +++ b/extensions/cli/src/tools/index.test.ts @@ -1,4 +1,4 @@ -import { getToolDisplayName, extractToolCalls } from "./index.js"; +import { extractToolCalls, getToolDisplayName } from "./index.js"; describe("tools/index utilities", () => { describe("getToolDisplayName", () => { diff --git a/extensions/cli/src/tools/index.ts b/extensions/cli/src/tools/index.tsx similarity index 94% rename from extensions/cli/src/tools/index.ts rename to extensions/cli/src/tools/index.tsx index f0c53fe44..76027adcd 100644 --- a/extensions/cli/src/tools/index.ts +++ b/extensions/cli/src/tools/index.tsx @@ -1,3 +1,7 @@ +// @ts-ignore +import { Text } from "ink"; +import * as React from "react"; + import { getServiceSync, MCPServiceState, @@ -207,13 +211,13 @@ export function validateToolCallArgsPresent(toolCall: ToolCall, tool: Tool) { * 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 + * @returns A React node with bolded tool name like "ToolName(arg)" or just "ToolName" if no args */ -export function formatToolCall(toolName: string, args?: any): string { +export function formatToolCall(toolName: string, args?: any): React.ReactNode { const displayName = getToolDisplayName(toolName); if (!args || Object.keys(args).length === 0) { - return displayName; + return {displayName}; } // Get the first argument value if it's a simple one @@ -238,5 +242,9 @@ export function formatToolCall(toolName: string, args?: any): string { } } - return `${displayName}(${formattedValue})`; + return ( + + {displayName}({formattedValue}) + + ); } diff --git a/extensions/cli/src/ui/ToolResultSummary.tsx b/extensions/cli/src/ui/ToolResultSummary.tsx index 296fec6e3..9abe25091 100644 --- a/extensions/cli/src/ui/ToolResultSummary.tsx +++ b/extensions/cli/src/ui/ToolResultSummary.tsx @@ -3,7 +3,7 @@ import path from "path"; import { Box, Text } from "ink"; import React from "react"; -import { getToolDisplayName } from "../tools/index.js"; +import { getToolDisplayName } from "src/tools/index.js"; import { ColoredDiff } from "./ColoredDiff.js"; import { ChecklistDisplay } from "./components/ChecklistDisplay.js"; diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index dffe90063..43ef4f98f 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -1,8 +1,9 @@ import { Box, Text } from "ink"; import React, { memo } from "react"; +import { formatToolCall } from "src/tools/index.js"; + import type { ChatHistoryItem } from "../../../../../core/index.js"; -import { formatToolCall } from "../../tools/index.js"; import { MarkdownRenderer } from "../MarkdownRenderer.js"; import { ToolResultSummary } from "../ToolResultSummary.js"; diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 69de1867a..3d3b25622 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -4,7 +4,6 @@ import type { ChatHistoryItem, Session } from "core/index.js"; import { getLastNPathParts } from "core/util/uri.js"; import { v4 as uuidv4 } from "uuid"; -import { initializeChatHistory } from "../../commands/chat.js"; import { compactChatHistory } from "../../compaction.js"; import { loadSession, @@ -20,11 +19,11 @@ import { shouldAutoCompact } from "../../util/tokenizer.js"; import { SlashCommandResult } from "./useChat.types.js"; /** - * Initialize chat history with proper system message + * Initialize chat history */ export async function initChatHistory( resume?: boolean, - additionalRules?: string[], + _additionalRules?: string[], ): Promise { if (resume) { const savedSession = loadSession(); @@ -33,11 +32,8 @@ export async function initChatHistory( } } - const history = await initializeChatHistory({ - resume, - rule: additionalRules, - }); - return history; + // Start with empty history - system message will be injected when needed + return []; } /** diff --git a/extensions/cli/vitest.config.ts b/extensions/cli/vitest.config.ts index 81b6c4b7f..32610d554 100644 --- a/extensions/cli/vitest.config.ts +++ b/extensions/cli/vitest.config.ts @@ -21,6 +21,11 @@ export default defineConfig({ testTimeout: 30000, hookTimeout: 30000, }, + esbuild: { + jsx: "transform", + jsxFactory: "React.createElement", + jsxFragment: "React.Fragment", + }, resolve: { extensions: [".js", ".ts", ".tsx", ".json"], },