From 711445aac73693aeeb86b6ef6945b4802df49e48 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 09:07:27 -0700 Subject: [PATCH 01/25] fix: multi-line bash tool call formatting --- extensions/cli/src/tools/formatters.test.ts | 22 +++++++++++++++++++++ extensions/cli/src/tools/index.ts | 4 ++++ 2 files changed, 26 insertions(+) diff --git a/extensions/cli/src/tools/formatters.test.ts b/extensions/cli/src/tools/formatters.test.ts index ff7e53d44..a9ca67ca9 100644 --- a/extensions/cli/src/tools/formatters.test.ts +++ b/extensions/cli/src/tools/formatters.test.ts @@ -62,6 +62,28 @@ describe("formatToolCall", () => { }), ).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'...)"); + + expect( + formatToolCall("Edit", { + old_string: "line 1\nline 2\nline 3", + new_string: "updated content", + }), + ).toBe("Edit(line 1...)"); + + // Test with empty first line + expect( + formatToolCall("Write", { + content: "\nSecond line\nThird line", + }), + ).toBe("Write(...)"); + }); }); describe("formatToolArgument", () => { diff --git a/extensions/cli/src/tools/index.ts b/extensions/cli/src/tools/index.ts index aa0f1b969..7b0e0b800 100644 --- a/extensions/cli/src/tools/index.ts +++ b/extensions/cli/src/tools/index.ts @@ -229,6 +229,10 @@ export function formatToolCall(toolName: string, args?: any): string { const valueLines = value.split("\n"); if (valueLines.length === 1) { formattedValue = formatToolArgument(value); + } else { + // For multi-line strings, show first line with ellipsis + const firstLine = valueLines[0].trim(); + formattedValue = firstLine ? `${formatToolArgument(firstLine)}...` : "..."; } } From 04cd89775ed9cf14d82662f018eeefd9d55bc04c Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 11:09:26 -0700 Subject: [PATCH 02/25] feat: generate session titles --- core/util/chatDescriber.ts | 77 +++++++++++++++++++ extensions/cli/src/commands/chat.ts | 38 ++++++++- .../cli/src/ui/hooks/useChat.helpers.ts | 38 +++++++++ .../src/ui/hooks/useChat.stream.helpers.ts | 25 +++++- extensions/cli/src/ui/hooks/useChat.ts | 2 + 5 files changed, 177 insertions(+), 3 deletions(-) diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 7235de0a3..085c09958 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -46,6 +46,83 @@ export class ChatDescriber { return removeQuotesAndEscapes(renderChatMessage(titleResponse)); } + // CLI-specific method that works with BaseLlmApi + static async describeWithBaseLlmApi( + llmApi: any, // BaseLlmApi - using any to avoid import issues + modelConfig: any, // ModelConfig - using any to avoid import issues + message: string, + ): Promise { + if (!ChatDescriber.prompt) { + return; + } + + // Clean up and distill the message we want to send to the LLM + message = removeCodeBlocksAndTrim(message); + + if (!message) { + return; + } + + try { + // Create the chat message in the unified format + const chatMessage = { + role: "user" as const, + content: ChatDescriber.prompt + message, + }; + + // Convert to OpenAI format - use a simple fallback to avoid import issues + let openaiMessages; + let defaultOptions = {}; + + try { + // Try to import CLI dependencies dynamically + const { convertFromUnifiedHistory } = await import("../../extensions/cli/src/messageConversion.js"); + const { getDefaultCompletionOptions } = await import("../../extensions/cli/src/streamChatResponse.types.js"); + + openaiMessages = convertFromUnifiedHistory([{ + message: chatMessage, + contextItems: [], + }]); + defaultOptions = getDefaultCompletionOptions(modelConfig.defaultCompletionOptions); + } catch { + // Fallback: use direct OpenAI format if imports fail + openaiMessages = [chatMessage]; + defaultOptions = {}; + } + + // Set up completion options for non-streaming + const completionOptions = { + model: modelConfig.model, + messages: openaiMessages, + max_tokens: ChatDescriber.maxTokens, + stream: false as const, + temperature: (defaultOptions as any)?.temperature, + frequency_penalty: (defaultOptions as any)?.frequency_penalty, + presence_penalty: (defaultOptions as any)?.presence_penalty, + top_p: (defaultOptions as any)?.top_p, + }; + + // Call the LLM + const titleResponse = await llmApi.chatCompletionNonStream( + completionOptions, + new AbortController().signal, + ); + + // Extract and clean up the response + if (titleResponse.choices && titleResponse.choices.length > 0) { + const content = titleResponse.choices[0].message.content; + if (content) { + return removeQuotesAndEscapes(content); + } + } + + return undefined; + } catch (error) { + console.debug("Error generating chat title:", error); + return undefined; + } + } + // // TODO: Allow the user to manually set specific/tailored prompts to generate their titles // static async setup() { // if(config?.prompt) { diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 5be2ef19d..3ffb00272 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -1,6 +1,7 @@ import { ModelConfig } from "@continuedev/config-yaml"; import chalk from "chalk"; 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"; @@ -17,7 +18,7 @@ import { sentryService } from "../sentry.js"; import { initializeServices } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; -import { loadSession, updateSessionHistory } from "../session.js"; +import { loadSession, updateSessionHistory, updateSessionTitle } from "../session.js"; import { streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import { posthogService } from "../telemetry/posthogService.js"; @@ -234,6 +235,33 @@ async function handleAutoCompaction( return result.compactionIndex; } +/** + * Helper to generate and update session title after first assistant response + */ +async function handleTitleGeneration( + assistantResponse: string, + llmApi: any, + model: ModelConfig, +): Promise { + try { + if (!assistantResponse) return; + + const generatedTitle = await ChatDescriber.describeWithBaseLlmApi( + llmApi, + model, + assistantResponse, + ); + + if (generatedTitle) { + updateSessionTitle(generatedTitle); + logger.debug("Generated session title:", generatedTitle); + } + } catch (error) { + // Don't fail the response if title generation fails + logger.debug("Session title generation failed:", error); + } +} + interface ProcessMessageOptions { userInput: string; chatHistory: ChatHistoryItem[]; @@ -243,6 +271,7 @@ interface ProcessMessageOptions { format?: "json"; silent?: boolean; compactionIndex?: number | null; + firstAssistantResponse?: boolean; } async function processMessage( @@ -257,6 +286,7 @@ async function processMessage( format, silent, compactionIndex: initialCompactionIndex, + firstAssistantResponse = false, } = options; let compactionIndex = initialCompactionIndex; // Check for slash commands in headless mode @@ -326,6 +356,11 @@ async function processMessage( // No need to sync back - streamChatResponse modifies chatHistory in place } + // Generate session title after first assistant response + if (firstAssistantResponse && finalResponse && finalResponse.trim()) { + await handleTitleGeneration(finalResponse, llmApi, model); + } + // In headless mode, only print the final response using safe stdout if (isHeadless && finalResponse && finalResponse.trim()) { let processedResponse = finalResponse; @@ -433,6 +468,7 @@ async function runHeadlessMode( format: options.format, silent: options.silent, compactionIndex, + firstAssistantResponse: isFirstMessage && !options.resume, // Only generate title for new conversations }); // Update compaction index if compaction occurred diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index c2c37c2f1..c5cbdc4c5 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -407,3 +407,41 @@ export async function handleAutoCompaction({ }; } } + +/** + * Generate a title for the session based on the first assistant response + */ +export async function generateSessionTitle( + assistantResponse: string, + llmApi: any, + model: any, + currentSessionTitle?: string, +): Promise { + // Only generate title for untitled sessions + if (currentSessionTitle && currentSessionTitle !== "Untitled Session") { + return undefined; + } + + if (!assistantResponse || !llmApi || !model) { + return undefined; + } + + try { + const { ChatDescriber } = await import("core/util/chatDescriber.js"); + const generatedTitle = await ChatDescriber.describeWithBaseLlmApi( + llmApi, + model, + assistantResponse, + ); + + logger.debug("Generated session title", { + original: currentSessionTitle, + generated: generatedTitle, + }); + + return generatedTitle; + } catch (error) { + logger.error("Failed to generate session title:", error); + return undefined; + } +} diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 1f697d6d8..70416471c 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -1,8 +1,14 @@ import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; +import { getCurrentSession, updateSessionTitle } from "../../session.js"; + +import { generateSessionTitle } from "./useChat.helpers.js"; + interface CreateStreamCallbacksOptions { setChatHistory: React.Dispatch>; setActivePermissionRequest: React.Dispatch>; + llmApi?: any; + model?: any; } /** @@ -11,12 +17,12 @@ interface CreateStreamCallbacksOptions { export function createStreamCallbacks( options: CreateStreamCallbacksOptions, ): any { - const { setChatHistory, setActivePermissionRequest } = options; + const { setChatHistory, setActivePermissionRequest, llmApi, model } = options; return { onContent: (_: string) => {}, - onContentComplete: (content: string) => { + onContentComplete: async (content: string) => { setChatHistory((prev) => [ ...prev, { @@ -28,6 +34,21 @@ export function createStreamCallbacks( }, }, ]); + + // Generate session title after first assistant response + if (content && llmApi && model) { + const currentSession = getCurrentSession(); + const generatedTitle = await generateSessionTitle( + content, + llmApi, + model, + currentSession.title, + ); + + if (generatedTitle) { + updateSessionTitle(generatedTitle); + } + } }, onToolStart: (toolName: string, toolArgs?: any) => { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index e0a813050..290fcd3b7 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -203,6 +203,8 @@ export function useChat({ const streamCallbacks = createStreamCallbacks({ setChatHistory, setActivePermissionRequest, + llmApi, + model, }); // Execute streaming chat response From 2b089bc83d7a03f7c518d1a68e0ac775b6ffde45 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 11:10:10 -0700 Subject: [PATCH 03/25] fix: solve bug loading organization visibility assistants --- extensions/cli/src/configLoader.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/configLoader.ts b/extensions/cli/src/configLoader.ts index 0a398d632..d587cc1af 100644 --- a/extensions/cli/src/configLoader.ts +++ b/extensions/cli/src/configLoader.ts @@ -18,6 +18,7 @@ import { getConfigUri, getOrganizationId, isEnvironmentAuthConfig, + loadAuthConfig, updateConfigUri, } from "./auth/workos.js"; import { CLIPlatformClient } from "./CLIPlatformClient.js"; @@ -358,7 +359,7 @@ async function loadAssistantSlug( uriType: "slug", fullSlug: { ownerSlug, packageSlug, versionSlug: "latest" }, }, - null, + getAccessToken(loadAuthConfig()), organizationId, apiClient, ); From ed52c875e4e93279c05e314398f1b0d007b2248e Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 11:10:26 -0700 Subject: [PATCH 04/25] fix: improve org switching experience --- extensions/cli/src/ui/TUIChat.tsx | 2 +- .../cli/src/ui/hooks/useConfigSelector.ts | 18 ++++-------------- extensions/cli/src/ui/hooks/useTUIChatHooks.ts | 4 ++-- 3 files changed, 7 insertions(+), 17 deletions(-) diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 6c474df77..768563bc0 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -231,7 +231,7 @@ const TUIChat: React.FC = ({ const { handleConfigSelect, handleModelSelect } = useSelectors( configPath, setChatHistory, - resetChatHistory, + handleClear ); // Session selection handler diff --git a/extensions/cli/src/ui/hooks/useConfigSelector.ts b/extensions/cli/src/ui/hooks/useConfigSelector.ts index 4d57695ca..a04d88694 100644 --- a/extensions/cli/src/ui/hooks/useConfigSelector.ts +++ b/extensions/cli/src/ui/hooks/useConfigSelector.ts @@ -20,14 +20,14 @@ interface UseConfigSelectorProps { content: string; messageType: "system"; }) => void; - onChatReset: () => void; + handleClear: () => void; } const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); export function useConfigSelector({ onMessage, - onChatReset, + handleClear }: UseConfigSelectorProps) { const { closeCurrentScreen } = useNavigation(); @@ -98,12 +98,6 @@ export function useConfigSelector({ // Only config path is changing, no organization switch needed await services.config.updateConfigPath(targetConfigPath); } else { - onMessage({ - role: "system", - content: `Switching to organization for ${config.name}...`, - messageType: "system" as const, - }); - // Switch organization first await services.auth.switchOrganization(config.organizationId ?? null); @@ -111,12 +105,8 @@ export function useConfigSelector({ // This avoids the double reload issue await services.config.updateConfigPath(targetConfigPath); } - - // Reset chat history - onChatReset(); - - // Clear the screen completely - process.stdout.write("\x1b[2J\x1b[H"); + + handleClear(); // Show success message onMessage({ diff --git a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts index f79f29083..7ae87bb06 100644 --- a/extensions/cli/src/ui/hooks/useTUIChatHooks.ts +++ b/extensions/cli/src/ui/hooks/useTUIChatHooks.ts @@ -98,7 +98,7 @@ export function useCurrentMode() { export function useSelectors( configPath: string | undefined, setChatHistory: React.Dispatch>, - resetChatHistory: () => void, + handleClear: () => void, ): { handleConfigSelect: (config: ConfigOption) => Promise; handleModelSelect: (model: ModelOption) => Promise; @@ -115,7 +115,7 @@ export function useSelectors( }, ]); }, - onChatReset: resetChatHistory, + handleClear, }); const { handleModelSelect } = useModelSelector({ From f3e26d121fc956f04dec770c2a48d90e72c28770 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 11:10:34 -0700 Subject: [PATCH 05/25] chore: package-lock.json update --- packages/openai-adapters/package-lock.json | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 046b1dc37..806a98f2a 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -12528,6 +12528,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" From 0a1187e223da46e222e8174437eeaaea17e8737c Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 11:22:57 -0700 Subject: [PATCH 06/25] fix: show /resume sessions in correct chronological order --- core/util/history.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/core/util/history.ts b/core/util/history.ts index a15b4f284..372fed88b 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -33,7 +33,8 @@ export class HistoryManager { sessions = sessions.filter((session: any) => { // Filter out old format return typeof session.session_id !== "string"; - }); + // We apply reverse() because they are in reverse chronological order + }).reverse(); // Apply limit and offset if (options.limit) { From e611cb6206be28d5d869c58d44ff52882e820296 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 11:24:57 -0700 Subject: [PATCH 07/25] fix: start a new session on /clear --- extensions/cli/src/session.test.ts | 49 +++++++++++++++++++ extensions/cli/src/session.ts | 21 ++++++++ .../cli/src/ui/hooks/useChat.clear.test.ts | 25 ++++++++++ .../cli/src/ui/hooks/useChat.helpers.ts | 6 ++- 4 files changed, 100 insertions(+), 1 deletion(-) diff --git a/extensions/cli/src/session.test.ts b/extensions/cli/src/session.test.ts index 35e042e74..0fb5f4525 100644 --- a/extensions/cli/src/session.test.ts +++ b/extensions/cli/src/session.test.ts @@ -2,6 +2,7 @@ import fs from "fs"; import os from "os"; import type { ChatHistoryItem, Session } from "core/index.js"; +import { v4 as uuidv4 } from "uuid"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { @@ -11,6 +12,7 @@ import { hasSession, loadSession, saveSession, + startNewSession, updateSessionHistory, updateSessionTitle, } from "./session.js"; @@ -352,4 +354,51 @@ describe("SessionManager", () => { expect(session.history[0].message.content).toBe("Test message"); }); }); + + describe("startNewSession", () => { + it("should clear the current session and create a new one", () => { + const firstSession = createSession(); + const firstSessionId = firstSession.sessionId; + + vi.mocked(uuidv4).mockReturnValue("new-uuid-456" as any); + + const secondSession = startNewSession(); + + expect(secondSession.sessionId).toBe("new-uuid-456"); + expect(secondSession.sessionId).not.toBe(firstSessionId); + expect(secondSession.title).toBe("Untitled Session"); + expect(secondSession.history).toEqual([]); + }); + + it("should create a new session with provided history", () => { + const history: ChatHistoryItem[] = [ + { + message: { + role: "system", + content: "You are a helpful assistant", + }, + contextItems: [], + }, + ]; + + vi.mocked(uuidv4).mockReturnValue("new-uuid-789" as any); + + const session = startNewSession(history); + + expect(session.sessionId).toBe("new-uuid-789"); + expect(session.history).toBe(history); + }); + + it("should set the new session as current", () => { + const originalSession = createSession(); + + vi.mocked(uuidv4).mockReturnValue("new-session-id" as any); + + const newSession = startNewSession(); + const currentSession = getCurrentSession(); + + expect(currentSession).toBe(newSession); + expect(currentSession).not.toBe(originalSession); + }); + }); }); diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index 89fc6dbf9..ea1b3e174 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -347,3 +347,24 @@ export function updateSessionTitle(title: string): void { export function getCurrentSession(): Session { return SessionManager.getInstance().getCurrentSession(); } + +/** + * Start a new session with a new sessionId + */ +export function startNewSession(history: ChatHistoryItem[] = []): Session { + const manager = SessionManager.getInstance(); + + // Clear the current session from memory (don't delete the file) + manager.clear(); + + // Create a new session with a new sessionId + const newSession: Session = { + sessionId: uuidv4(), + title: "Untitled Session", + workspaceDirectory: process.cwd(), + history, + }; + + manager.setSession(newSession); + return newSession; +} diff --git a/extensions/cli/src/ui/hooks/useChat.clear.test.ts b/extensions/cli/src/ui/hooks/useChat.clear.test.ts index 91f7e62d4..39517aa2a 100644 --- a/extensions/cli/src/ui/hooks/useChat.clear.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.clear.test.ts @@ -2,9 +2,18 @@ import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { convertToUnifiedHistory } from "../../messageConversion.js"; +import { startNewSession } from "../../session.js"; import { processSlashCommandResult } from "./useChat.helpers.js"; + +// Mock the session module +vi.mock("../../session.js", () => ({ + loadSession: vi.fn(), + updateSessionHistory: vi.fn(), + startNewSession: vi.fn(), +})); + describe("useChat clear command", () => { let mockSetChatHistory: ReturnType; let mockExit: ReturnType; @@ -41,6 +50,11 @@ describe("useChat clear command", () => { // Verify that onClear was called expect(mockOnClear).toHaveBeenCalledOnce(); + // Verify that a new session was started with the system message + expect(startNewSession).toHaveBeenCalledWith([ + chatHistory[0], // The system message ChatHistoryItem + ]); + // Verify that chat history was reset (keeping only system message) expect(mockSetChatHistory).toHaveBeenCalledWith([ chatHistory[0], // The system message ChatHistoryItem @@ -81,6 +95,11 @@ describe("useChat clear command", () => { }); }).not.toThrow(); + // Verify that a new session was started with the system message + expect(startNewSession).toHaveBeenCalledWith([ + chatHistory[0], // The system message ChatHistoryItem + ]); + // Verify that history is still reset expect(mockSetChatHistory).toHaveBeenCalledWith([ chatHistory[0], // The system message ChatHistoryItem @@ -111,6 +130,9 @@ describe("useChat clear command", () => { onClear: mockOnClear, }); + // Verify that a new session was started with the system message + expect(startNewSession).toHaveBeenCalledWith([systemHistoryItem]); + // Should keep only the system message expect(mockSetChatHistory).toHaveBeenCalledWith([systemHistoryItem]); expect(mockOnClear).toHaveBeenCalledOnce(); @@ -130,6 +152,9 @@ describe("useChat clear command", () => { onClear: mockOnClear, }); + // Verify that a new session was started with empty history + expect(startNewSession).toHaveBeenCalledWith([]); + // Should set empty history when no system message exists expect(mockSetChatHistory).toHaveBeenCalledWith([]); expect(mockOnClear).toHaveBeenCalledOnce(); diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index c5cbdc4c5..8e65998ec 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -6,7 +6,7 @@ import { v4 as uuidv4 } from "uuid"; import { initializeChatHistory } from "../../commands/chat.js"; import { compactChatHistory } from "../../compaction.js"; -import { loadSession, updateSessionHistory } from "../../session.js"; +import { loadSession, updateSessionHistory, startNewSession } from "../../session.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; import { formatError } from "../../util/formatError.js"; @@ -177,6 +177,10 @@ export function processSlashCommandResult({ (item) => item.message.role === "system", ); const newHistory = systemMessage ? [systemMessage] : []; + + // Start a new session with a new sessionId + startNewSession(newHistory); + setChatHistory(newHistory); // Reset intro message state to show it again after clearing From 7e2f038fbbd3311eb533ff77f6d7271c7f9295f1 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 11:25:04 -0700 Subject: [PATCH 08/25] chore: packge-lock again --- packages/openai-adapters/package-lock.json | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/openai-adapters/package-lock.json b/packages/openai-adapters/package-lock.json index 806a98f2a..046b1dc37 100644 --- a/packages/openai-adapters/package-lock.json +++ b/packages/openai-adapters/package-lock.json @@ -12528,7 +12528,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", "dev": true, - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" From d0ab8b5e9170f17aec1118b6f2caf3a77d7f2081 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 11:27:42 -0700 Subject: [PATCH 09/25] chore: format --- core/util/chatDescriber.ts | 26 ++++++++++++------- core/util/history.ts | 12 +++++---- extensions/cli/src/commands/chat.ts | 6 ++++- extensions/cli/src/session.ts | 6 ++--- extensions/cli/src/tools/index.ts | 4 ++- extensions/cli/src/ui/TUIChat.tsx | 2 +- .../cli/src/ui/hooks/useChat.clear.test.ts | 1 - .../cli/src/ui/hooks/useChat.helpers.ts | 12 ++++++--- .../src/ui/hooks/useChat.stream.helpers.ts | 2 +- .../cli/src/ui/hooks/useConfigSelector.ts | 4 +-- package-lock.json | 2 +- 11 files changed, 48 insertions(+), 29 deletions(-) diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 085c09958..4c23de69e 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -73,17 +73,25 @@ export class ChatDescriber { // Convert to OpenAI format - use a simple fallback to avoid import issues let openaiMessages; let defaultOptions = {}; - + try { // Try to import CLI dependencies dynamically - const { convertFromUnifiedHistory } = await import("../../extensions/cli/src/messageConversion.js"); - const { getDefaultCompletionOptions } = await import("../../extensions/cli/src/streamChatResponse.types.js"); - - openaiMessages = convertFromUnifiedHistory([{ - message: chatMessage, - contextItems: [], - }]); - defaultOptions = getDefaultCompletionOptions(modelConfig.defaultCompletionOptions); + const { convertFromUnifiedHistory } = await import( + "../../extensions/cli/src/messageConversion.js" + ); + const { getDefaultCompletionOptions } = await import( + "../../extensions/cli/src/streamChatResponse.types.js" + ); + + openaiMessages = convertFromUnifiedHistory([ + { + message: chatMessage, + contextItems: [], + }, + ]); + defaultOptions = getDefaultCompletionOptions( + modelConfig.defaultCompletionOptions, + ); } catch { // Fallback: use direct OpenAI format if imports fail openaiMessages = [chatMessage]; diff --git a/core/util/history.ts b/core/util/history.ts index 372fed88b..b8ad13f92 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -30,11 +30,13 @@ export class HistoryManager { const content = fs.readFileSync(filepath, "utf8"); let sessions = safeParseArray(content) ?? []; - sessions = sessions.filter((session: any) => { - // Filter out old format - return typeof session.session_id !== "string"; - // We apply reverse() because they are in reverse chronological order - }).reverse(); + sessions = sessions + .filter((session: any) => { + // Filter out old format + return typeof session.session_id !== "string"; + // We apply reverse() because they are in reverse chronological order + }) + .reverse(); // Apply limit and offset if (options.limit) { diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 3ffb00272..c6e48fa6e 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -18,7 +18,11 @@ import { sentryService } from "../sentry.js"; import { initializeServices } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; -import { loadSession, updateSessionHistory, updateSessionTitle } from "../session.js"; +import { + loadSession, + updateSessionHistory, + updateSessionTitle, +} from "../session.js"; import { streamChatResponse } from "../streamChatResponse.js"; import { constructSystemMessage } from "../systemMessage.js"; import { posthogService } from "../telemetry/posthogService.js"; diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index ea1b3e174..cf94dc829 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -353,10 +353,10 @@ export function getCurrentSession(): Session { */ export function startNewSession(history: ChatHistoryItem[] = []): Session { const manager = SessionManager.getInstance(); - + // Clear the current session from memory (don't delete the file) manager.clear(); - + // Create a new session with a new sessionId const newSession: Session = { sessionId: uuidv4(), @@ -364,7 +364,7 @@ export function startNewSession(history: ChatHistoryItem[] = []): Session { workspaceDirectory: process.cwd(), history, }; - + manager.setSession(newSession); return newSession; } diff --git a/extensions/cli/src/tools/index.ts b/extensions/cli/src/tools/index.ts index 7b0e0b800..f0c53fe44 100644 --- a/extensions/cli/src/tools/index.ts +++ b/extensions/cli/src/tools/index.ts @@ -232,7 +232,9 @@ export function formatToolCall(toolName: string, args?: any): string { } else { // For multi-line strings, show first line with ellipsis const firstLine = valueLines[0].trim(); - formattedValue = firstLine ? `${formatToolArgument(firstLine)}...` : "..."; + formattedValue = firstLine + ? `${formatToolArgument(firstLine)}...` + : "..."; } } diff --git a/extensions/cli/src/ui/TUIChat.tsx b/extensions/cli/src/ui/TUIChat.tsx index 768563bc0..3c0ac26df 100644 --- a/extensions/cli/src/ui/TUIChat.tsx +++ b/extensions/cli/src/ui/TUIChat.tsx @@ -231,7 +231,7 @@ const TUIChat: React.FC = ({ const { handleConfigSelect, handleModelSelect } = useSelectors( configPath, setChatHistory, - handleClear + handleClear, ); // Session selection handler diff --git a/extensions/cli/src/ui/hooks/useChat.clear.test.ts b/extensions/cli/src/ui/hooks/useChat.clear.test.ts index 39517aa2a..fe8c2ed8d 100644 --- a/extensions/cli/src/ui/hooks/useChat.clear.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.clear.test.ts @@ -6,7 +6,6 @@ import { startNewSession } from "../../session.js"; import { processSlashCommandResult } from "./useChat.helpers.js"; - // Mock the session module vi.mock("../../session.js", () => ({ loadSession: vi.fn(), diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 8e65998ec..69de1867a 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -6,7 +6,11 @@ import { v4 as uuidv4 } from "uuid"; import { initializeChatHistory } from "../../commands/chat.js"; import { compactChatHistory } from "../../compaction.js"; -import { loadSession, updateSessionHistory, startNewSession } from "../../session.js"; +import { + loadSession, + updateSessionHistory, + startNewSession, +} from "../../session.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { telemetryService } from "../../telemetry/telemetryService.js"; import { formatError } from "../../util/formatError.js"; @@ -177,10 +181,10 @@ export function processSlashCommandResult({ (item) => item.message.role === "system", ); const newHistory = systemMessage ? [systemMessage] : []; - + // Start a new session with a new sessionId startNewSession(newHistory); - + setChatHistory(newHistory); // Reset intro message state to show it again after clearing @@ -437,7 +441,7 @@ export async function generateSessionTitle( model, assistantResponse, ); - + logger.debug("Generated session title", { original: currentSessionTitle, generated: generatedTitle, diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 70416471c..d6d1ecc4b 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -44,7 +44,7 @@ export function createStreamCallbacks( model, currentSession.title, ); - + if (generatedTitle) { updateSessionTitle(generatedTitle); } diff --git a/extensions/cli/src/ui/hooks/useConfigSelector.ts b/extensions/cli/src/ui/hooks/useConfigSelector.ts index a04d88694..bed4efa8f 100644 --- a/extensions/cli/src/ui/hooks/useConfigSelector.ts +++ b/extensions/cli/src/ui/hooks/useConfigSelector.ts @@ -27,7 +27,7 @@ const CONFIG_PATH = path.join(env.continueHome, "config.yaml"); export function useConfigSelector({ onMessage, - handleClear + handleClear, }: UseConfigSelectorProps) { const { closeCurrentScreen } = useNavigation(); @@ -105,7 +105,7 @@ export function useConfigSelector({ // This avoids the double reload issue await services.config.updateConfigPath(targetConfigPath); } - + handleClear(); // Show success message diff --git a/package-lock.json b/package-lock.json index b4289d422..c00b3f307 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "continue", + "name": "wt-generate-message-titles-in-cli", "lockfileVersion": 3, "requires": true, "packages": { From 27e016e47ff22bf8f6261460d5346d323fc8c41c Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 13:32:55 -0700 Subject: [PATCH 10/25] fix: show ascii art in static area --- extensions/cli/src/commands/chat.ts | 3 --- extensions/cli/src/ui/IntroMessage.tsx | 5 +++++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index c6e48fa6e..bbc417c05 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -514,9 +514,6 @@ export async function chat(prompt?: string, options: ChatOptions = {}) { console.log(chalk.green("✓ Setup complete! Starting chat...")); } - // Show ASCII art and version for TUI mode - console.log(getDisplayableAsciiArt()); - // Start TUI with skipOnboarding since we already handled it const tuiOptions: any = { initialPrompt: prompt, diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx index 52d226ad0..039299b8e 100644 --- a/extensions/cli/src/ui/IntroMessage.tsx +++ b/extensions/cli/src/ui/IntroMessage.tsx @@ -2,6 +2,7 @@ import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; import { Box, Text } from "ink"; import React, { useMemo } from "react"; +import { getDisplayableAsciiArt } from "../asciiArt.js"; import { MCPService } from "../services/MCPService.js"; import { isModelCapable } from "../utils/modelCapability.js"; @@ -41,6 +42,10 @@ const IntroMessage: React.FC = ({ return ( + {/* ASCII Art */} + {getDisplayableAsciiArt()} + + {/* Agent name */} {config && ( From 6ab59ad1d2de7020967bce3629f0bc47a3db7419 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 13:38:26 -0700 Subject: [PATCH 11/25] feat: more info in /info slash command --- extensions/cli/src/slashCommands.info.test.ts | 138 ++++++++++++++++++ extensions/cli/src/slashCommands.ts | 24 +++ 2 files changed, 162 insertions(+) create mode 100644 extensions/cli/src/slashCommands.info.test.ts diff --git a/extensions/cli/src/slashCommands.info.test.ts b/extensions/cli/src/slashCommands.info.test.ts new file mode 100644 index 000000000..e332ad15c --- /dev/null +++ b/extensions/cli/src/slashCommands.info.test.ts @@ -0,0 +1,138 @@ +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 * as sessionModule from "./session.js"; +import { posthogService } from "./telemetry/posthogService.js"; + +// Mock all dependencies +vi.mock("./auth/workos.js"); +vi.mock("./version.js"); +vi.mock("./session.js"); +vi.mock("./telemetry/posthogService.js"); + +vi.mock("./services/index.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + services: { + config: { + getState: vi.fn(), + }, + model: { + getModelInfo: vi.fn(), + }, + }, + }; +}); + +describe("handleSlashCommands - /info", () => { + const mockAssistant = { + prompts: [], + }; + + beforeEach(() => { + vi.clearAllMocks(); + + // Mock process.cwd + vi.spyOn(process, "cwd").mockReturnValue("/test/working/directory"); + + // Mock posthog + vi.mocked(posthogService.capture).mockReturnValue(undefined); + + // Mock version + vi.mocked(versionModule.getVersion).mockReturnValue("1.2.3"); + + // Mock session + vi.mocked(sessionModule.getSessionFilePath).mockReturnValue( + "/test/session.json", + ); + }); + + it("should include version and working directory in output", async () => { + // Mock auth as not authenticated + vi.mocked(workosModule.isAuthenticated).mockReturnValue(false); + + // Mock config service + const mockConfigState = { + config: { name: "test-config" }, + configPath: "/test/config.yaml", + }; + vi.mocked(services.config.getState).mockReturnValue(mockConfigState); + vi.mocked(services.model.getModelInfo).mockReturnValue({ + provider: "openai", + name: "gpt-4", + }); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result).toBeDefined(); + expect(result?.output).toContain("CLI Information:"); + expect(result?.output).toContain("Version: 1.2.3"); + expect(result?.output).toContain( + "Working Directory: /test/working/directory", + ); + expect(result?.output).toContain("Configuration:"); + expect(result?.output).toContain("Model: openai/gpt-4"); + expect(result?.exit).toBe(false); + }); + + it("should handle authenticated user info", async () => { + // Mock auth as authenticated + vi.mocked(workosModule.isAuthenticated).mockReturnValue(true); + vi.mocked(workosModule.loadAuthConfig).mockReturnValue({ + userEmail: "test@example.com", + userId: "test-user", + } as any); + vi.mocked(workosModule.isAuthenticatedConfig).mockReturnValue(true); + + // Mock config service + const mockConfigState = { + config: { name: "test-config" }, + configPath: "/test/config.yaml", + }; + vi.mocked(services.config.getState).mockReturnValue(mockConfigState); + vi.mocked(services.model.getModelInfo).mockReturnValue({ + provider: "anthropic", + name: "claude-3-sonnet", + }); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result?.output).toContain("Authentication:"); + expect(result?.output).toContain("Email: test@example.com"); + expect(result?.output).toContain("Model: anthropic/claude-3-sonnet"); + }); + + it("should handle missing model info gracefully", async () => { + // Mock auth as not authenticated + vi.mocked(workosModule.isAuthenticated).mockReturnValue(false); + + // Mock config service with no model info + const mockConfigState = { + config: { name: "test-config" }, + configPath: "/test/config.yaml", + }; + vi.mocked(services.config.getState).mockReturnValue(mockConfigState); + vi.mocked(services.model.getModelInfo).mockReturnValue(null); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result?.output).toContain("Model: Not available"); + }); + + it("should handle config service error", async () => { + // Mock auth as not authenticated + vi.mocked(workosModule.isAuthenticated).mockReturnValue(false); + + // Mock config service throwing error + vi.mocked(services.config.getState).mockImplementation(() => { + throw new Error("Service not available"); + }); + + const result = await handleSlashCommands("/info", mockAssistant); + + expect(result?.output).toContain("Configuration service not available"); + }); +}); diff --git a/extensions/cli/src/slashCommands.ts b/extensions/cli/src/slashCommands.ts index dc24c30bc..ce25b0091 100644 --- a/extensions/cli/src/slashCommands.ts +++ b/extensions/cli/src/slashCommands.ts @@ -11,6 +11,7 @@ import { reloadService, SERVICE_NAMES, services } from "./services/index.js"; import { getSessionFilePath } from "./session.js"; import { posthogService } from "./telemetry/posthogService.js"; import { SlashCommandResult } from "./ui/hooks/useChat.types.js"; +import { getVersion } from "./version.js"; type CommandHandler = ( args: string[], @@ -102,22 +103,33 @@ async function handleInfo() { const infoLines = []; + // Version and working directory info + const version = getVersion(); + const cwd = process.cwd(); + + infoLines.push(chalk.white("CLI Information:")); + infoLines.push(` Version: ${chalk.green(version)}`); + infoLines.push(` Working Directory: ${chalk.blue(cwd)}`); + // Auth info if (isAuthenticated()) { const config = loadAuthConfig(); if (config && isAuthenticatedConfig(config)) { const email = config.userEmail || config.userId; const org = "(no org)"; // Organization info not available in AuthenticatedConfig + infoLines.push(""); infoLines.push(chalk.white("Authentication:")); infoLines.push(` Email: ${chalk.green(email)}`); infoLines.push(` Organization: ${chalk.cyan(org)}`); } else { + infoLines.push(""); infoLines.push(chalk.white("Authentication:")); infoLines.push( ` ${chalk.yellow("Authenticated via environment variable")}`, ); } } else { + infoLines.push(""); infoLines.push(chalk.white("Authentication:")); infoLines.push(` ${chalk.red("Not logged in")}`); } @@ -135,6 +147,18 @@ async function handleInfo() { if (configState.configPath) { infoLines.push(` Path: ${chalk.blue(configState.configPath)}`); } + + // Add current model info + try { + const modelInfo = services.model?.getModelInfo(); + if (modelInfo) { + infoLines.push(` Model: ${chalk.cyan(modelInfo.name)}`); + } else { + infoLines.push(` Model: ${chalk.red("Not available")}`); + } + } catch { + infoLines.push(` Model: ${chalk.red("Error retrieving model info")}`); + } } catch { infoLines.push(""); infoLines.push(chalk.white("Configuration:")); From 5f61503e7f3e42518f0360db5cb38a8d6ec83d80 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 13:43:10 -0700 Subject: [PATCH 12/25] fix: update plan mode system message --- extensions/cli/src/systemMessage.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index 77742956d..14bc9c5c2 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -172,6 +172,12 @@ export async function constructSystemMessage( // Construct the comprehensive system message let systemMessage = baseSystemMessage; + // Add plan mode specific instructions if in plan mode + if (currentMode === "plan") { + systemMessage += + '\nYou are operating in plan mode, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files.\n'; + } + // In headless mode, add instructions to be concise and only provide final answers if (headless) { systemMessage += ` @@ -191,13 +197,6 @@ Example response format: }`; } - // Add plan mode specific instructions if in plan mode - if (currentMode === "plan") { - systemMessage += ` - -PLAN MODE: You are operating in plan mode, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files.`; - } - // Add rules section if we have any rules or agent content if (agentContent || processedRules.length > 0) { systemMessage += '\n\n'; From a46ce4327fefe90b9e2fa893ccd36b3472aa7708 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 13:44:01 -0700 Subject: [PATCH 13/25] fix: update plan mode system message again --- extensions/cli/src/systemMessage.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/extensions/cli/src/systemMessage.ts b/extensions/cli/src/systemMessage.ts index 14bc9c5c2..3c1e1fcde 100644 --- a/extensions/cli/src/systemMessage.ts +++ b/extensions/cli/src/systemMessage.ts @@ -175,7 +175,7 @@ export async function constructSystemMessage( // Add plan mode specific instructions if in plan mode if (currentMode === "plan") { systemMessage += - '\nYou are operating in plan mode, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files.\n'; + '\nYou are operating in _Plan Mode_, which means that your goal is to help the user investigate their ideas and develop a plan before taking action. You only have access to read-only tools and should not attempt to circumvent them to write / delete / create files. For example, it is not acceptable to use the Bash tool to write to files.\n'; } // In headless mode, add instructions to be concise and only provide final answers From 3edec65985a96d295c214d00bdf67b8031f55e6e Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 13:57:48 -0700 Subject: [PATCH 14/25] feat: \ + enter for new line --- extensions/cli/src/ui/UserInput.tsx | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 826f821a7..cb0014952 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -386,6 +386,27 @@ const UserInput: React.FC = ({ const handleEnterKey = (key: any): boolean => { if (key.return && !key.shift) { + // Check for backslash continuation + const beforeCursor = textBuffer.text.slice(0, cursorPosition); + const trimmedBeforeCursor = beforeCursor.trimEnd(); + + if (trimmedBeforeCursor.endsWith("\\")) { + // Handle backslash continuation: remove the trailing "\" and add newline + const beforeBackslash = trimmedBeforeCursor.slice(0, -1); + const afterCursor = textBuffer.text.slice(cursorPosition); + const newText = beforeBackslash + "\n" + afterCursor; + const newCursorPos = beforeBackslash.length + 1; + + textBuffer.setText(newText); + textBuffer.setCursor(newCursorPos); + setInputText(newText); + setCursorPosition(newCursorPos); + updateSlashCommandState(newText, newCursorPos); + updateFileSearchState(newText, newCursorPos); + return true; + } + + // Normal Enter behavior - submit if there's content if (textBuffer.text.trim() && !isWaitingForResponse) { // Expand all paste blocks before submitting textBuffer.expandAllPasteBlocks(); From f018112d39119fee9c65e47ae66ff75098f7b16a Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 15:05:10 -0700 Subject: [PATCH 15/25] fix: correctly handle failed tool calls --- extensions/cli/src/streamChatResponse.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/extensions/cli/src/streamChatResponse.ts b/extensions/cli/src/streamChatResponse.ts index 25ab84bc0..f481bb802 100644 --- a/extensions/cli/src/streamChatResponse.ts +++ b/extensions/cli/src/streamChatResponse.ts @@ -1,6 +1,7 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatHistoryItem, ToolStatus } from "core/index.js"; +import { stripImages } from "core/util/messageContent.js"; import * as dotenv from "dotenv"; import type { ChatCompletionTool } from "openai/resources.mjs"; @@ -128,8 +129,9 @@ async function handleToolCalls( errorChatEntries.forEach((errorEntry) => { chatHistory.push( createHistoryItem({ - role: "assistant", - content: errorEntry.content || "", + role: "tool", + content: stripImages(errorEntry.content) || "", + toolCallId: errorEntry.tool_call_id, }), ); }); From f69ba1767898dd7226243a9bcce76acd87fb60a3 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 15:57:40 -0700 Subject: [PATCH 16/25] 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"], }, From 6a6a0b388e515e7bbcbba561abeb8a64d062a4fc Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 15:58:32 -0700 Subject: [PATCH 17/25] fix: delete unecessary build options --- extensions/cli/vitest.config.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/extensions/cli/vitest.config.ts b/extensions/cli/vitest.config.ts index 32610d554..81b6c4b7f 100644 --- a/extensions/cli/vitest.config.ts +++ b/extensions/cli/vitest.config.ts @@ -21,11 +21,6 @@ export default defineConfig({ testTimeout: 30000, hookTimeout: 30000, }, - esbuild: { - jsx: "transform", - jsxFactory: "React.createElement", - jsxFragment: "React.Fragment", - }, resolve: { extensions: [".js", ".ts", ".tsx", ".json"], }, From ec592c7229f168cd4fcffc8523695881dc3ded9d Mon Sep 17 00:00:00 2001 From: Nate Sesti <33237525+sestinj@users.noreply.github.com> Date: Wed, 27 Aug 2025 16:02:49 -0700 Subject: [PATCH 18/25] Update core/util/history.ts Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com> --- core/util/history.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/util/history.ts b/core/util/history.ts index b8ad13f92..447249ded 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -34,7 +34,7 @@ export class HistoryManager { .filter((session: any) => { // Filter out old format return typeof session.session_id !== "string"; - // We apply reverse() because they are in reverse chronological order + // Reverse to show newest first; sessions.json is chronological by creation }) .reverse(); From 8d1dc7ff41518732d6acb3f4adc1dc43a6d92136 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 21:07:57 -0700 Subject: [PATCH 19/25] fix: build problems --- extensions/cli/src/tools/ToolCallTitle.tsx | 50 +++++++++++++++++++ extensions/cli/src/tools/index.tsx | 46 ----------------- .../cli/src/ui/components/MemoizedMessage.tsx | 4 +- .../ui/components/ToolPermissionSelector.tsx | 7 ++- 4 files changed, 55 insertions(+), 52 deletions(-) create mode 100644 extensions/cli/src/tools/ToolCallTitle.tsx diff --git a/extensions/cli/src/tools/ToolCallTitle.tsx b/extensions/cli/src/tools/ToolCallTitle.tsx new file mode 100644 index 000000000..90c5dea3f --- /dev/null +++ b/extensions/cli/src/tools/ToolCallTitle.tsx @@ -0,0 +1,50 @@ +import { Text } from "ink"; +import React from "react"; + +import { formatToolArgument } from "./formatters.js"; + +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 React node with bolded tool name like "ToolName(arg)" or just "ToolName" if no args + */ +export function ToolCallTitle(props: { toolName: string; args?: any }) { + const { toolName, args } = props; + + const displayName = getToolDisplayName(toolName); + + if (!args || Object.keys(args).length === 0) { + return {displayName}; + } + + // Get the first argument value if it's a simple one + let formattedValue = ""; + const [key, value] = Object.entries(args)[0]; + if ( + key.toLowerCase().includes("path") || + typeof value === "number" || + typeof value === "boolean" + ) { + formattedValue = formatToolArgument(value); + } else if (typeof value === "string") { + const valueLines = value.split("\n"); + if (valueLines.length === 1) { + formattedValue = formatToolArgument(value); + } else { + // For multi-line strings, show first line with ellipsis + const firstLine = valueLines[0].trim(); + formattedValue = firstLine + ? `${formatToolArgument(firstLine)}...` + : "..."; + } + } + + return ( + + {displayName}({formattedValue}) + + ); +} diff --git a/extensions/cli/src/tools/index.tsx b/extensions/cli/src/tools/index.tsx index 76027adcd..a4cb3dcb7 100644 --- a/extensions/cli/src/tools/index.tsx +++ b/extensions/cli/src/tools/index.tsx @@ -1,7 +1,4 @@ // @ts-ignore -import { Text } from "ink"; -import * as React from "react"; - import { getServiceSync, MCPServiceState, @@ -15,7 +12,6 @@ import { logger } from "../util/logger.js"; import { editTool } from "./edit.js"; import { exitTool } from "./exit.js"; import { fetchTool } from "./fetch.js"; -import { formatToolArgument } from "./formatters.js"; import { listFilesTool } from "./listFiles.js"; import { multiEditTool } from "./multiEdit.js"; import { readFileTool } from "./readFile.js"; @@ -206,45 +202,3 @@ 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 React node with bolded tool name like "ToolName(arg)" or just "ToolName" if no args - */ -export function formatToolCall(toolName: string, args?: any): React.ReactNode { - const displayName = getToolDisplayName(toolName); - - if (!args || Object.keys(args).length === 0) { - return {displayName}; - } - - // Get the first argument value if it's a simple one - let formattedValue = ""; - const [key, value] = Object.entries(args)[0]; - if ( - key.toLowerCase().includes("path") || - typeof value === "number" || - typeof value === "boolean" - ) { - formattedValue = formatToolArgument(value); - } else if (typeof value === "string") { - const valueLines = value.split("\n"); - if (valueLines.length === 1) { - formattedValue = formatToolArgument(value); - } else { - // For multi-line strings, show first line with ellipsis - const firstLine = valueLines[0].trim(); - formattedValue = firstLine - ? `${formatToolArgument(firstLine)}...` - : "..."; - } - } - - return ( - - {displayName}({formattedValue}) - - ); -} diff --git a/extensions/cli/src/ui/components/MemoizedMessage.tsx b/extensions/cli/src/ui/components/MemoizedMessage.tsx index 43ef4f98f..58a95616d 100644 --- a/extensions/cli/src/ui/components/MemoizedMessage.tsx +++ b/extensions/cli/src/ui/components/MemoizedMessage.tsx @@ -1,7 +1,7 @@ import { Box, Text } from "ink"; import React, { memo } from "react"; -import { formatToolCall } from "src/tools/index.js"; +import { ToolCallTitle } from "src/tools/ToolCallTitle.js"; import type { ChatHistoryItem } from "../../../../../core/index.js"; import { MarkdownRenderer } from "../MarkdownRenderer.js"; @@ -93,7 +93,7 @@ export const MemoizedMessage = memo( {" "} - {formatToolCall(toolName, toolArgs)} + diff --git a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx index e5e9da0ca..46abde7d2 100644 --- a/extensions/cli/src/ui/components/ToolPermissionSelector.tsx +++ b/extensions/cli/src/ui/components/ToolPermissionSelector.tsx @@ -1,7 +1,8 @@ import { Box, Text, useInput } from "ink"; import React, { useState } from "react"; -import { formatToolCall } from "../../tools/index.js"; +import { ToolCallTitle } from "src/tools/ToolCallTitle.js"; + import { ToolCallPreview } from "../../tools/types.js"; import { ToolPreview } from "./ToolPreview.js"; @@ -101,8 +102,6 @@ export const ToolPermissionSelector: React.FC = ({ } }); - const toolCallDisplay = formatToolCall(toolName, toolArgs); - return ( = ({ borderColor="magenta" > - {toolCallDisplay} + {/* Show preview of what the tool will do */} From d1c4e6458030a30d944e4c10c46114166149ed70 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 21:08:02 -0700 Subject: [PATCH 20/25] fix remove old tests --- extensions/cli/src/tools/formatters.test.ts | 194 -------------------- 1 file changed, 194 deletions(-) delete mode 100644 extensions/cli/src/tools/formatters.test.ts diff --git a/extensions/cli/src/tools/formatters.test.ts b/extensions/cli/src/tools/formatters.test.ts deleted file mode 100644 index 1bef86dbd..000000000 --- a/extensions/cli/src/tools/formatters.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { render } from "ink-testing-library"; -import React from "react"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -import { formatToolArgument } from "./formatters.js"; - -import { formatToolCall } from "./index.js"; - -describe("formatToolCall", () => { - beforeEach(() => { - // Mock process.cwd to return a consistent value - vi.spyOn(process, "cwd").mockReturnValue("/Users/test/project"); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("should format tool name without arguments", () => { - 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", () => { - const writeResult = render( - React.createElement( - () => - formatToolCall("Write", { - filepath: "README.md", - }) as React.ReactElement, - ), - ); - 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", () => { - const writeResult = render( - React.createElement( - () => - formatToolCall("Write", { - filepath: "/Users/test/project/README.md", - }) as React.ReactElement, - ), - ); - expect(writeResult.lastFrame()).toBe("Write(README.md)"); - - 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", () => { - 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", () => { - 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", () => { - 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", () => { - 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'...)"); - - 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 - const writeResult = render( - React.createElement( - () => - formatToolCall("Write", { - content: "\nSecond line\nThird line", - }) as React.ReactElement, - ), - ); - expect(writeResult.lastFrame()).toBe("Write(...)"); - }); -}); - -describe("formatToolArgument", () => { - beforeEach(() => { - vi.spyOn(process, "cwd").mockReturnValue("/Users/test/project"); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("should return empty string for null/undefined", () => { - expect(formatToolArgument(null)).toBe(""); - expect(formatToolArgument(undefined)).toBe(""); - }); - - it("should convert absolute paths to relative", () => { - expect(formatToolArgument("/Users/test/project/README.md")).toBe( - "README.md", - ); - expect(formatToolArgument("/Users/test/project/src/index.ts")).toBe( - "src/index.ts", - ); - }); - - it("should preserve relative paths", () => { - expect(formatToolArgument("README.md")).toBe("README.md"); - expect(formatToolArgument("./src/index.ts")).toBe("./src/index.ts"); - }); - - it("should handle non-string values", () => { - expect(formatToolArgument(123)).toBe("123"); - expect(formatToolArgument(true)).toBe("true"); - expect(formatToolArgument({ key: "value" })).toBe("[object Object]"); - }); -}); From 626a3c66a0e58f7271a3f0d221bc6c00a5316104 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 21:32:23 -0700 Subject: [PATCH 21/25] fix: types, imports, and formatting --- core/util/chatDescriber.ts | 37 +-- .../src => core/util}/messageConversion.ts | 8 +- extensions/cli/src/commands/chat.ts | 4 +- extensions/cli/src/commands/serve.helpers.ts | 4 +- extensions/cli/src/commands/serve.ts | 2 +- .../cli/src/compaction.infiniteLoop.test.ts | 6 +- .../src/compaction.pruneLastMessage.test.ts | 4 +- extensions/cli/src/compaction.test.ts | 4 +- extensions/cli/src/compaction.ts | 4 +- extensions/cli/src/messageConversion.test.ts | 3 +- extensions/cli/src/stream/handleToolCalls.ts | 224 ++++++++++++++++ .../streamChatResponse.autoCompaction.test.ts | 20 +- .../streamChatResponse.autoCompaction.ts | 10 +- .../streamChatResponse.getAllTools.test.ts | 5 +- .../streamChatResponse.helpers.ts | 19 +- .../streamChatResponse.modeSwitch.test.ts | 11 +- .../{ => stream}/streamChatResponse.test.ts | 25 +- .../src/{ => stream}/streamChatResponse.ts | 247 ++---------------- .../{ => stream}/streamChatResponse.types.ts | 2 +- .../ui/__tests__/TUIChat.planModeBug.test.tsx | 3 +- .../cli/src/ui/hooks/useChat.clear.test.ts | 2 +- .../src/ui/hooks/useChat.remote.helpers.ts | 2 +- .../src/ui/hooks/useChat.stream.helpers.ts | 4 +- 23 files changed, 324 insertions(+), 326 deletions(-) rename {extensions/cli/src => core/util}/messageConversion.ts (98%) create mode 100644 extensions/cli/src/stream/handleToolCalls.ts rename extensions/cli/src/{ => stream}/streamChatResponse.autoCompaction.test.ts (91%) rename extensions/cli/src/{ => stream}/streamChatResponse.autoCompaction.ts (94%) rename extensions/cli/src/{ => stream}/streamChatResponse.getAllTools.test.ts (97%) rename extensions/cli/src/{ => stream}/streamChatResponse.helpers.ts (96%) rename extensions/cli/src/{ => stream}/streamChatResponse.modeSwitch.test.ts (96%) rename extensions/cli/src/{ => stream}/streamChatResponse.test.ts (96%) rename extensions/cli/src/{ => stream}/streamChatResponse.ts (58%) rename extensions/cli/src/{ => stream}/streamChatResponse.types.ts (95%) diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index 4c23de69e..9c5c5c96b 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -5,6 +5,7 @@ import { removeCodeBlocksAndTrim, removeQuotesAndEscapes } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import type { IMessenger } from "../protocol/messenger"; import { renderChatMessage } from "./messageContent"; +import { convertFromUnifiedHistory } from "./messageConversion"; export class ChatDescriber { static maxTokens = 12; @@ -71,32 +72,12 @@ export class ChatDescriber { }; // Convert to OpenAI format - use a simple fallback to avoid import issues - let openaiMessages; - let defaultOptions = {}; - - try { - // Try to import CLI dependencies dynamically - const { convertFromUnifiedHistory } = await import( - "../../extensions/cli/src/messageConversion.js" - ); - const { getDefaultCompletionOptions } = await import( - "../../extensions/cli/src/streamChatResponse.types.js" - ); - - openaiMessages = convertFromUnifiedHistory([ - { - message: chatMessage, - contextItems: [], - }, - ]); - defaultOptions = getDefaultCompletionOptions( - modelConfig.defaultCompletionOptions, - ); - } catch { - // Fallback: use direct OpenAI format if imports fail - openaiMessages = [chatMessage]; - defaultOptions = {}; - } + const openaiMessages = convertFromUnifiedHistory([ + { + message: chatMessage, + contextItems: [], + }, + ]); // Set up completion options for non-streaming const completionOptions = { @@ -104,10 +85,6 @@ export class ChatDescriber { messages: openaiMessages, max_tokens: ChatDescriber.maxTokens, stream: false as const, - temperature: (defaultOptions as any)?.temperature, - frequency_penalty: (defaultOptions as any)?.frequency_penalty, - presence_penalty: (defaultOptions as any)?.presence_penalty, - top_p: (defaultOptions as any)?.top_p, }; // Call the LLM diff --git a/extensions/cli/src/messageConversion.ts b/core/util/messageConversion.ts similarity index 98% rename from extensions/cli/src/messageConversion.ts rename to core/util/messageConversion.ts index d182f5425..cc561cb84 100644 --- a/extensions/cli/src/messageConversion.ts +++ b/core/util/messageConversion.ts @@ -5,6 +5,7 @@ * format and the unified ChatHistoryItem format from the core package. */ +import type { ChatCompletionMessageParam } from "openai/resources.mjs"; import type { AssistantChatMessage, ChatHistoryItem, @@ -14,8 +15,7 @@ import type { ToolCall, ToolCallState, ToolStatus, -} from "core/index.js"; -import type { ChatCompletionMessageParam } from "openai/resources.mjs"; +} from "../index.js"; /** * Convert ChatCompletionMessageParam to ChatMessage @@ -230,7 +230,7 @@ function handleToolResult( if (!historyItems[lastAssistantIndex].toolCallStates) return; const toolState = historyItems[lastAssistantIndex].toolCallStates?.find( - (ts) => ts.toolCallId === unifiedMessage.toolCallId, + (ts: ToolCallState) => ts.toolCallId === unifiedMessage.toolCallId, ); if (toolState) { @@ -311,7 +311,7 @@ export function convertFromUnifiedHistory( ) { const contextContent = item.contextItems .map( - (contextItem) => + (contextItem: ContextItemWithId) => `\n${contextItem.content}\n\n\n`, ) .join(""); diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 44ebc9cff..c62b656c4 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -22,7 +22,7 @@ import { updateSessionHistory, updateSessionTitle, } from "../session.js"; -import { streamChatResponse } from "../streamChatResponse.js"; +import { streamChatResponse } from "../stream/streamChatResponse.js"; import { posthogService } from "../telemetry/posthogService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { startTUIChat } from "../ui/index.js"; @@ -157,7 +157,7 @@ async function handleAutoCompaction( format?: "json", ): Promise { const { handleAutoCompaction: coreAutoCompaction } = await import( - "../streamChatResponse.autoCompaction.js" + "../stream/streamChatResponse.autoCompaction.js" ); // Custom callbacks for headless mode console output diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts index 7180955c3..01cc1e032 100644 --- a/extensions/cli/src/commands/serve.helpers.ts +++ b/extensions/cli/src/commands/serve.helpers.ts @@ -5,8 +5,8 @@ import type { ToolStatus, } from "core/index.js"; -import { streamChatResponse } from "../streamChatResponse.js"; -import { StreamCallbacks } from "../streamChatResponse.types.js"; +import { streamChatResponse } from "../stream/streamChatResponse.js"; +import { StreamCallbacks } from "../stream/streamChatResponse.types.js"; // Modified version of streamChatResponse that supports interruption export async function streamChatResponseWithInterruption( diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 97c06cda0..2a07017af 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -3,11 +3,11 @@ import { promisify } from "util"; import chalk from "chalk"; import type { ChatHistoryItem } from "core/index.js"; +import { convertFromUnifiedHistory } from "core/util/messageConversion.js"; import express, { Request, Response } from "express"; import { getAssistantSlug } from "../auth/workos.js"; import { processCommandFlags } from "../flags/flagProcessor.js"; -import { convertFromUnifiedHistory } from "../messageConversion.js"; import { toolPermissionManager } from "../permissions/permissionManager.js"; import { getService, diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts index a153cfb28..14ac4d862 100644 --- a/extensions/cli/src/compaction.infiniteLoop.test.ts +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -1,10 +1,10 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; -import { describe, it, expect, vi } from "vitest"; +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; +import { describe, expect, it, vi } from "vitest"; import { compactChatHistory } from "./compaction.js"; -import { convertToUnifiedHistory } from "./messageConversion.js"; -import { streamChatResponse } from "./streamChatResponse.js"; +import { streamChatResponse } from "./stream/streamChatResponse.js"; // Mock the dependencies vi.mock("./streamChatResponse.js", () => ({ diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts index 1152837e8..a9ed83da4 100644 --- a/extensions/cli/src/compaction.pruneLastMessage.test.ts +++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts @@ -1,7 +1,7 @@ -import { describe, it, expect } from "vitest"; +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; +import { describe, expect, it } from "vitest"; import { pruneLastMessage } from "./compaction.js"; -import { convertToUnifiedHistory } from "./messageConversion.js"; import { logger } from "./util/logger.js"; describe("pruneLastMessage", () => { diff --git a/extensions/cli/src/compaction.test.ts b/extensions/cli/src/compaction.test.ts index e23424c67..394d26893 100644 --- a/extensions/cli/src/compaction.test.ts +++ b/extensions/cli/src/compaction.test.ts @@ -1,6 +1,7 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatHistoryItem } from "core/index.js"; +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; import { describe, expect, it, vi } from "vitest"; import { @@ -8,8 +9,7 @@ import { findCompactionIndex, getHistoryForLLM, } from "./compaction.js"; -import { convertToUnifiedHistory } from "./messageConversion.js"; -import { streamChatResponse } from "./streamChatResponse.js"; +import { streamChatResponse } from "./stream/streamChatResponse.js"; // Mock the streamChatResponse function vi.mock("./streamChatResponse.js", () => ({ diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index 29d7e3f70..3edbe0260 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -2,8 +2,8 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatHistoryItem } from "core/index.js"; -import { streamChatResponse } from "./streamChatResponse.js"; -import { StreamCallbacks } from "./streamChatResponse.types.js"; +import { streamChatResponse } from "./stream/streamChatResponse.js"; +import { StreamCallbacks } from "./stream/streamChatResponse.types.js"; import { logger } from "./util/logger.js"; import { countChatHistoryTokens, diff --git a/extensions/cli/src/messageConversion.test.ts b/extensions/cli/src/messageConversion.test.ts index 3a4903294..45e7de2c2 100644 --- a/extensions/cli/src/messageConversion.test.ts +++ b/extensions/cli/src/messageConversion.test.ts @@ -1,6 +1,5 @@ import type { ChatHistoryItem } from "core/index.js"; - -import { convertFromUnifiedHistory } from "./messageConversion.js"; +import { convertFromUnifiedHistory } from "core/util/messageConversion.js"; describe("convertFromUnifiedHistory", () => { it("should expand contextItems into user message content", () => { diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts new file mode 100644 index 000000000..aa37a25d7 --- /dev/null +++ b/extensions/cli/src/stream/handleToolCalls.ts @@ -0,0 +1,224 @@ +import type { ChatHistoryItem, ToolStatus } from "core/index.js"; +import { stripImages } from "core/util/messageContent.js"; +import { createHistoryItem } from "core/util/messageConversion.js"; +import type { ChatCompletionTool } from "openai/resources.mjs"; + +import { filterExcludedTools } from "../permissions/index.js"; +import { + getServiceSync, + MCPServiceState, + MCPTool, + SERVICE_NAMES, +} from "../services/index.js"; +import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; +import { getAllBuiltinTools, ToolCall } from "../tools/index.js"; +import { logger } from "../util/logger.js"; + +import { + executeStreamedToolCalls, + preprocessStreamedToolCalls, +} from "./streamChatResponse.helpers.js"; +import { StreamCallbacks } from "./streamChatResponse.types.js"; + +export async function handleToolCalls( + toolCalls: ToolCall[], + chatHistory: ChatHistoryItem[], + content: string, + callbacks: StreamCallbacks | undefined, + isHeadless: boolean, +): Promise { + if (toolCalls.length === 0) { + if (content) { + chatHistory.push( + createHistoryItem({ + role: "assistant", + content, + }), + ); + } + return false; + } + + // Create tool call states for the ChatHistoryItem + const toolCallStates = toolCalls.map((tc) => ({ + toolCallId: tc.id, + toolCall: { + id: tc.id, + type: "function" as const, + function: { + name: tc.name, + arguments: JSON.stringify(tc.arguments), + }, + }, + status: "generated" as ToolStatus, + parsedArgs: tc.arguments, + })); + + // Create assistant message with tool calls + const assistantMessage = { + role: "assistant" as const, + content: content || "", + toolCalls: toolCalls.map((tc) => ({ + id: tc.id, + type: "function" as const, + function: { + name: tc.name, + arguments: JSON.stringify(tc.arguments), + }, + })), + }; + + chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); + + // First preprocess the tool calls + const { preprocessedCalls, errorChatEntries } = + await preprocessStreamedToolCalls(toolCalls, callbacks); + + // Add any preprocessing errors to chat history + // Convert error entries from OpenAI format to ChatHistoryItem format + errorChatEntries.forEach((errorEntry) => { + chatHistory.push( + createHistoryItem({ + role: "tool", + content: stripImages(errorEntry.content) || "", + toolCallId: errorEntry.tool_call_id, + }), + ); + }); + + // Execute the valid preprocessed tool calls + const { chatHistoryEntries: toolResults, hasRejection } = + await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless); + + if (isHeadless && hasRejection) { + logger.debug( + "Tool call rejected in headless mode - returning current content", + ); + return true; // Signal early return needed + } + + // Convert tool results from OpenAI format to ChatHistoryItem format + // and add them to the chat history + toolResults.forEach((toolResult) => { + // Find the corresponding tool call state to update + const lastAssistantIndex = chatHistory.findLastIndex( + (item) => item.message.role === "assistant" && item.toolCallStates, + ); + + if ( + lastAssistantIndex >= 0 && + chatHistory[lastAssistantIndex].toolCallStates + ) { + const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( + (ts) => ts.toolCallId === toolResult.tool_call_id, + ); + + if (toolState) { + toolState.status = hasRejection ? "canceled" : "done"; + toolState.output = [ + { + content: + typeof toolResult.content === "string" ? toolResult.content : "", + name: `Tool Result`, + description: "Tool execution result", + }, + ]; + } + } + }); + return false; +} + +export async function getAllTools() { + // Get all available tool names + const allBuiltinTools = getAllBuiltinTools(); + const builtinToolNames = allBuiltinTools.map((tool) => tool.name); + + let mcpTools: MCPTool[] = []; + let mcpToolNames: string[] = []; + const mcpServiceResult = getServiceSync(SERVICE_NAMES.MCP); + if (mcpServiceResult.state === "ready") { + mcpTools = mcpServiceResult?.value?.tools ?? []; + mcpToolNames = mcpTools.map((t) => t.name); + } else { + // MCP is lazy + // throw new Error("MCP Service not initialized"); + } + + const allToolNames = [...builtinToolNames, ...mcpToolNames]; + + // Check if the ToolPermissionService is ready + const permissionsServiceResult = getServiceSync( + SERVICE_NAMES.TOOL_PERMISSIONS, + ); + + let allowedToolNames: string[]; + if ( + permissionsServiceResult.state === "ready" && + permissionsServiceResult.value + ) { + // Filter out excluded tools based on permissions + allowedToolNames = filterExcludedTools( + allToolNames, + permissionsServiceResult.value.permissions, + ); + } else { + // Service not ready - this is a critical error since tools should only be + // requested after services are properly initialized + logger.error( + "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue", + ); + throw new Error( + "ToolPermissionService not initialized. Services must be initialized before requesting tools.", + ); + } + + const allowedToolNamesSet = new Set(allowedToolNames); + + // Filter builtin tools + const allowedBuiltinTools = allBuiltinTools.filter((tool) => + allowedToolNamesSet.has(tool.name), + ); + + const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({ + type: "function" as const, + function: { + name: tool.name, + description: tool.description, + parameters: { + type: "object", + properties: Object.fromEntries( + Object.entries(tool.parameters).map(([key, param]) => [ + key, + { + type: param.type, + description: param.description, + items: param.items, + }, + ]), + ), + required: Object.entries(tool.parameters) + .filter(([_, param]) => param.required) + .map(([key, _]) => key), + }, + }, + })); + + // Add filtered MCP tools + const allowedMcpTools = mcpTools.filter((tool) => + allowedToolNamesSet.has(tool.name), + ); + + allTools.push( + ...allowedMcpTools.map((tool) => ({ + type: "function" as const, + function: { + name: tool.name, + description: tool.description, + parameters: tool.inputSchema, + }, + })), + ); + + return allTools; +} diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts similarity index 91% rename from extensions/cli/src/streamChatResponse.autoCompaction.test.ts rename to extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts index b154ea5e1..b3f550e1d 100644 --- a/extensions/cli/src/streamChatResponse.autoCompaction.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts @@ -1,7 +1,7 @@ import type { ChatHistoryItem } from "core/index.js"; +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { convertToUnifiedHistory } from "./messageConversion.js"; import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; // Mock dependencies @@ -69,7 +69,7 @@ describe("handleAutoCompaction", () => { }); it("should return original history when auto-compaction is not needed", async () => { - const { shouldAutoCompact } = await import("./util/tokenizer.js"); + const { shouldAutoCompact } = await import("../util/tokenizer.js"); vi.mocked(shouldAutoCompact).mockReturnValue(false); const result = await handleAutoCompaction( @@ -90,10 +90,10 @@ describe("handleAutoCompaction", () => { it("should perform auto-compaction when context limit is approaching", async () => { const { shouldAutoCompact, getAutoCompactMessage } = await import( - "./util/tokenizer.js" + "../util/tokenizer.js" ); - const { compactChatHistory } = await import("./compaction.js"); - const { updateSessionHistory } = await import("./session.js"); + const { compactChatHistory } = await import("../compaction.js"); + const { updateSessionHistory } = await import("../session.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); @@ -157,10 +157,10 @@ describe("handleAutoCompaction", () => { it("should handle compaction errors gracefully", async () => { const { shouldAutoCompact, getAutoCompactMessage } = await import( - "./util/tokenizer.js" + "../util/tokenizer.js" ); - const { compactChatHistory } = await import("./compaction.js"); - const { logger } = await import("./util/logger.js"); + const { compactChatHistory } = await import("../compaction.js"); + const { logger } = await import("../util/logger.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); @@ -200,9 +200,9 @@ describe("handleAutoCompaction", () => { it("should not call system message callback in headless mode", async () => { const { shouldAutoCompact, getAutoCompactMessage } = await import( - "./util/tokenizer.js" + "../util/tokenizer.js" ); - const { compactChatHistory } = await import("./compaction.js"); + const { compactChatHistory } = await import("../compaction.js"); vi.mocked(shouldAutoCompact).mockReturnValue(true); vi.mocked(getAutoCompactMessage).mockReturnValue("Auto-compacting..."); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts similarity index 94% rename from extensions/cli/src/streamChatResponse.autoCompaction.ts rename to extensions/cli/src/stream/streamChatResponse.autoCompaction.ts index 9d66bb0bc..4e55a2cd5 100644 --- a/extensions/cli/src/streamChatResponse.autoCompaction.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.ts @@ -3,11 +3,11 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatHistoryItem } from "core/index.js"; import React from "react"; -import { compactChatHistory } from "./compaction.js"; -import { updateSessionHistory } from "./session.js"; -import { formatError } from "./util/formatError.js"; -import { logger } from "./util/logger.js"; -import { getAutoCompactMessage, shouldAutoCompact } from "./util/tokenizer.js"; +import { compactChatHistory } from "../compaction.js"; +import { updateSessionHistory } from "../session.js"; +import { formatError } from "../util/formatError.js"; +import { logger } from "../util/logger.js"; +import { getAutoCompactMessage, shouldAutoCompact } from "../util/tokenizer.js"; interface AutoCompactionCallbacks { // For streaming mode diff --git a/extensions/cli/src/streamChatResponse.getAllTools.test.ts b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts similarity index 97% rename from extensions/cli/src/streamChatResponse.getAllTools.test.ts rename to extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts index d71f75023..8d8eb68a3 100644 --- a/extensions/cli/src/streamChatResponse.getAllTools.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.getAllTools.test.ts @@ -5,8 +5,9 @@ import { initializeServices, SERVICE_NAMES, serviceContainer, -} from "./services/index.js"; -import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; +} from "../services/index.js"; +import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; + import { getAllTools } from "./streamChatResponse.js"; describe("getAllTools - Tool Filtering", () => { diff --git a/extensions/cli/src/streamChatResponse.helpers.ts b/extensions/cli/src/stream/streamChatResponse.helpers.ts similarity index 96% rename from extensions/cli/src/streamChatResponse.helpers.ts rename to extensions/cli/src/stream/streamChatResponse.helpers.ts index 4a90aedca..4ac0a9e88 100644 --- a/extensions/cli/src/streamChatResponse.helpers.ts +++ b/extensions/cli/src/stream/streamChatResponse.helpers.ts @@ -2,21 +2,22 @@ import { ChatCompletionToolMessageParam } from "openai/resources/chat/completions.mjs"; -import { checkToolPermission } from "./permissions/permissionChecker.js"; -import { toolPermissionManager } from "./permissions/permissionManager.js"; -import { ToolCallRequest } from "./permissions/types.js"; -import { StreamCallbacks } from "./streamChatResponse.types.js"; -import { telemetryService } from "./telemetry/telemetryService.js"; -import { calculateTokenCost } from "./telemetry/utils.js"; +import { checkToolPermission } from "../permissions/permissionChecker.js"; +import { toolPermissionManager } from "../permissions/permissionManager.js"; +import { ToolCallRequest } from "../permissions/types.js"; +import { telemetryService } from "../telemetry/telemetryService.js"; +import { calculateTokenCost } from "../telemetry/utils.js"; import { executeToolCall, getAllBuiltinTools, getAvailableTools, Tool, validateToolCallArgsPresent, -} from "./tools/index.js"; -import { PreprocessedToolCall, ToolCall } from "./tools/types.js"; -import { logger } from "./util/logger.js"; +} from "../tools/index.js"; +import { PreprocessedToolCall, ToolCall } from "../tools/types.js"; +import { logger } from "../util/logger.js"; + +import { StreamCallbacks } from "./streamChatResponse.types.js"; // Helper function to handle permission denied export function handlePermissionDenied( diff --git a/extensions/cli/src/streamChatResponse.modeSwitch.test.ts b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts similarity index 96% rename from extensions/cli/src/streamChatResponse.modeSwitch.test.ts rename to extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts index d662e1744..f5a9e74bd 100644 --- a/extensions/cli/src/streamChatResponse.modeSwitch.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.modeSwitch.test.ts @@ -1,12 +1,13 @@ -import { describe, expect, test, vi, beforeEach } from "vitest"; +import { beforeEach, describe, expect, test, vi } from "vitest"; import { - serviceContainer, SERVICE_NAMES, initializeServices, -} from "./services/index.js"; -import { modeService } from "./services/ModeService.js"; -import { getAllTools } from "./streamChatResponse.js"; + serviceContainer, +} from "../services/index.js"; +import { modeService } from "../services/ModeService.js"; + +import { getAllTools } from "./handleToolCalls.js"; describe("streamChatResponse - Mode Switch During Streaming", () => { beforeEach(async () => { diff --git a/extensions/cli/src/streamChatResponse.test.ts b/extensions/cli/src/stream/streamChatResponse.test.ts similarity index 96% rename from extensions/cli/src/streamChatResponse.test.ts rename to extensions/cli/src/stream/streamChatResponse.test.ts index 56fb42a23..05fd1a6cf 100644 --- a/extensions/cli/src/streamChatResponse.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.test.ts @@ -4,17 +4,18 @@ import type { ChatHistoryItem } from "core/index.js"; import type { ChatCompletionChunk } from "openai/resources/chat/completions.mjs"; import { vi } from "vitest"; -import { toolPermissionManager } from "./permissions/permissionManager.js"; +import { toolPermissionManager } from "../permissions/permissionManager.js"; +import { ToolCall } from "../tools/index.js"; +import { readFileTool } from "../tools/readFile.js"; +import { searchCodeTool } from "../tools/searchCode.js"; +import { PreprocessedToolCall } from "../tools/types.js"; +import { writeFileTool } from "../tools/writeFile.js"; + import { executeStreamedToolCalls, preprocessStreamedToolCalls, } from "./streamChatResponse.helpers.js"; import { processStreamingResponse } from "./streamChatResponse.js"; -import { ToolCall } from "./tools/index.js"; -import { readFileTool } from "./tools/readFile.js"; -import { searchCodeTool } from "./tools/searchCode.js"; -import { PreprocessedToolCall } from "./tools/types.js"; -import { writeFileTool } from "./tools/writeFile.js"; // Test the chunk processing logic that was identified as buggy describe("processStreamingResponse - content preservation", () => { @@ -438,7 +439,7 @@ describe.skip("preprocessStreamedToolCalls", () => { it("handles tool preprocessing errors correctly", async () => { // Set the spy to throw an error - const toolsModule = await import("./tools/index.js"); + const toolsModule = await import("../tools/index.js"); vi.spyOn(toolsModule, "validateToolCallArgsPresent").mockImplementationOnce( () => { throw new Error("Missing required argument"); @@ -510,12 +511,12 @@ describe.skip("executeStreamedToolCalls", () => { it("executes tool calls with allowed permissions", async () => { // Setup spies instead of mocks - const permissionsModule = await import("./permissions/index.js"); + const permissionsModule = await import("../permissions/index.js"); vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ permission: "allow", }); - const toolsModule = await import("./tools/index.js"); + const toolsModule = await import("../tools/index.js"); const mockedExecuteToolCall = vi .spyOn(toolsModule, "executeToolCall") .mockResolvedValue("Tool execution successful"); @@ -559,7 +560,7 @@ describe.skip("executeStreamedToolCalls", () => { it("handles permission denied correctly", async () => { // Setup permission to ask - const permissionsModule = await import("./permissions/index.js"); + const permissionsModule = await import("../permissions/index.js"); vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ permission: "ask", }); @@ -646,12 +647,12 @@ describe.skip("executeStreamedToolCalls", () => { it("handles tool execution errors", async () => { // Setup spies - const permissionsModule = await import("./permissions/index.js"); + const permissionsModule = await import("../permissions/index.js"); vi.spyOn(permissionsModule, "checkToolPermission").mockReturnValue({ permission: "allow", }); - const toolsModule = await import("./tools/index.js"); + const toolsModule = await import("../tools/index.js"); vi.spyOn(toolsModule, "executeToolCall").mockRejectedValue( new Error("Execution failed"), ); diff --git a/extensions/cli/src/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts similarity index 58% rename from extensions/cli/src/streamChatResponse.ts rename to extensions/cli/src/stream/streamChatResponse.ts index 290c3bb07..0f5f5edd5 100644 --- a/extensions/cli/src/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -1,27 +1,27 @@ import { ModelConfig } from "@continuedev/config-yaml"; import { BaseLlmApi } from "@continuedev/openai-adapters"; -import type { ChatHistoryItem, ToolStatus } from "core/index.js"; -import { stripImages } from "core/util/messageContent.js"; +import type { ChatHistoryItem } from "core/index.js"; +import { convertFromUnifiedHistoryWithSystemMessage } from "core/util/messageConversion.js"; import * as dotenv from "dotenv"; -import type { ChatCompletionTool } from "openai/resources.mjs"; +import type { + ChatCompletionMessageParam, + ChatCompletionTool, +} from "openai/resources.mjs"; +import { getServiceSync, SERVICE_NAMES } from "../services/index.js"; +import { systemMessageService } from "../services/SystemMessageService.js"; +import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; +import { telemetryService } from "../telemetry/telemetryService.js"; +import { ToolCall } from "../tools/index.js"; import { - convertFromUnifiedHistoryWithSystemMessage, - createHistoryItem, -} from "./messageConversion.js"; -import { filterExcludedTools } from "./permissions/index.js"; -import { - getServiceSync, - MCPServiceState, - MCPTool, - SERVICE_NAMES, -} from "./services/index.js"; -import { systemMessageService } from "./services/SystemMessageService.js"; -import type { ToolPermissionServiceState } from "./services/ToolPermissionService.js"; + chatCompletionStreamWithBackoff, + withExponentialBackoff, +} from "../util/exponentialBackoff.js"; +import { logger } from "../util/logger.js"; + +import { getAllTools, handleToolCalls } from "./handleToolCalls.js"; import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; import { - executeStreamedToolCalls, - preprocessStreamedToolCalls, processChunkContent, processToolCallDelta, recordStreamTelemetry, @@ -31,13 +31,6 @@ import { getDefaultCompletionOptions, StreamCallbacks, } from "./streamChatResponse.types.js"; -import { telemetryService } from "./telemetry/telemetryService.js"; -import { getAllBuiltinTools, ToolCall } from "./tools/index.js"; -import { - chatCompletionStreamWithBackoff, - withExponentialBackoff, -} from "./util/exponentialBackoff.js"; -import { logger } from "./util/logger.js"; dotenv.config(); @@ -71,209 +64,6 @@ function handleContentDisplay( } } -async function handleToolCalls( - toolCalls: ToolCall[], - chatHistory: ChatHistoryItem[], - content: string, - callbacks: StreamCallbacks | undefined, - isHeadless: boolean, -): Promise { - if (toolCalls.length === 0) { - if (content) { - chatHistory.push( - createHistoryItem({ - role: "assistant", - content, - }), - ); - } - return false; - } - - // Create tool call states for the ChatHistoryItem - const toolCallStates = toolCalls.map((tc) => ({ - toolCallId: tc.id, - toolCall: { - id: tc.id, - type: "function" as const, - function: { - name: tc.name, - arguments: JSON.stringify(tc.arguments), - }, - }, - status: "generated" as ToolStatus, - parsedArgs: tc.arguments, - })); - - // Create assistant message with tool calls - const assistantMessage = { - role: "assistant" as const, - content: content || "", - toolCalls: toolCalls.map((tc) => ({ - id: tc.id, - type: "function" as const, - function: { - name: tc.name, - arguments: JSON.stringify(tc.arguments), - }, - })), - }; - - chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); - - // First preprocess the tool calls - const { preprocessedCalls, errorChatEntries } = - await preprocessStreamedToolCalls(toolCalls, callbacks); - - // Add any preprocessing errors to chat history - // Convert error entries from OpenAI format to ChatHistoryItem format - errorChatEntries.forEach((errorEntry) => { - chatHistory.push( - createHistoryItem({ - role: "tool", - content: stripImages(errorEntry.content) || "", - toolCallId: errorEntry.tool_call_id, - }), - ); - }); - - // Execute the valid preprocessed tool calls - const { chatHistoryEntries: toolResults, hasRejection } = - await executeStreamedToolCalls(preprocessedCalls, callbacks, isHeadless); - - if (isHeadless && hasRejection) { - logger.debug( - "Tool call rejected in headless mode - returning current content", - ); - return true; // Signal early return needed - } - - // Convert tool results from OpenAI format to ChatHistoryItem format - // and add them to the chat history - toolResults.forEach((toolResult) => { - // Find the corresponding tool call state to update - const lastAssistantIndex = chatHistory.findLastIndex( - (item) => item.message.role === "assistant" && item.toolCallStates, - ); - - if ( - lastAssistantIndex >= 0 && - chatHistory[lastAssistantIndex].toolCallStates - ) { - const toolState = chatHistory[lastAssistantIndex].toolCallStates.find( - (ts) => ts.toolCallId === toolResult.tool_call_id, - ); - - if (toolState) { - toolState.status = hasRejection ? "canceled" : "done"; - toolState.output = [ - { - content: - typeof toolResult.content === "string" ? toolResult.content : "", - name: `Tool Result`, - description: "Tool execution result", - }, - ]; - } - } - }); - return false; -} - -export async function getAllTools() { - // Get all available tool names - const allBuiltinTools = getAllBuiltinTools(); - const builtinToolNames = allBuiltinTools.map((tool) => tool.name); - - let mcpTools: MCPTool[] = []; - let mcpToolNames: string[] = []; - const mcpServiceResult = getServiceSync(SERVICE_NAMES.MCP); - if (mcpServiceResult.state === "ready") { - mcpTools = mcpServiceResult?.value?.tools ?? []; - mcpToolNames = mcpTools.map((t) => t.name); - } else { - // MCP is lazy - // throw new Error("MCP Service not initialized"); - } - - const allToolNames = [...builtinToolNames, ...mcpToolNames]; - - // Check if the ToolPermissionService is ready - const permissionsServiceResult = getServiceSync( - SERVICE_NAMES.TOOL_PERMISSIONS, - ); - - let allowedToolNames: string[]; - if ( - permissionsServiceResult.state === "ready" && - permissionsServiceResult.value - ) { - // Filter out excluded tools based on permissions - allowedToolNames = filterExcludedTools( - allToolNames, - permissionsServiceResult.value.permissions, - ); - } else { - // Service not ready - this is a critical error since tools should only be - // requested after services are properly initialized - logger.error( - "ToolPermissionService not ready in getAllTools - this indicates a service initialization timing issue", - ); - throw new Error( - "ToolPermissionService not initialized. Services must be initialized before requesting tools.", - ); - } - - const allowedToolNamesSet = new Set(allowedToolNames); - - // Filter builtin tools - const allowedBuiltinTools = allBuiltinTools.filter((tool) => - allowedToolNamesSet.has(tool.name), - ); - - const allTools: ChatCompletionTool[] = allowedBuiltinTools.map((tool) => ({ - type: "function" as const, - function: { - name: tool.name, - description: tool.description, - parameters: { - type: "object", - properties: Object.fromEntries( - Object.entries(tool.parameters).map(([key, param]) => [ - key, - { - type: param.type, - description: param.description, - items: param.items, - }, - ]), - ), - required: Object.entries(tool.parameters) - .filter(([_, param]) => param.required) - .map(([key, _]) => key), - }, - }, - })); - - // Add filtered MCP tools - const allowedMcpTools = mcpTools.filter((tool) => - allowedToolNamesSet.has(tool.name), - ); - - allTools.push( - ...allowedMcpTools.map((tool) => ({ - type: "function" as const, - function: { - name: tool.name, - description: tool.description, - parameters: tool.inputSchema, - }, - })), - ); - - return allTools; -} - // Helper function to process a single chunk interface ProcessChunkOptions { chunk: any; @@ -362,7 +152,7 @@ export async function processStreamingResponse( const openaiChatHistory = convertFromUnifiedHistoryWithSystemMessage( chatHistory, systemMessage, - ); + ) as ChatCompletionMessageParam[]; const requestStartTime = Date.now(); const streamFactory = async (retryAbortSignal: AbortSignal) => { @@ -610,3 +400,4 @@ export async function streamChatResponse( // Otherwise, return the full response return isHeadless ? finalResponse : fullResponse; } +export { getAllTools }; diff --git a/extensions/cli/src/streamChatResponse.types.ts b/extensions/cli/src/stream/streamChatResponse.types.ts similarity index 95% rename from extensions/cli/src/streamChatResponse.types.ts rename to extensions/cli/src/stream/streamChatResponse.types.ts index b219849fb..405505eee 100644 --- a/extensions/cli/src/streamChatResponse.types.ts +++ b/extensions/cli/src/stream/streamChatResponse.types.ts @@ -2,7 +2,7 @@ import { CompletionOptions } from "@continuedev/config-yaml"; import type { ToolStatus } from "core/index.js"; import type { ChatCompletionCreateParamsStreaming } from "openai/resources.mjs"; -import { ToolCallPreview } from "./tools/types.js"; +import { ToolCallPreview } from "../tools/types.js"; export interface StreamCallbacks { onContent?: (content: string) => void; diff --git a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx index 8dc12557a..77b8161ba 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.planModeBug.test.tsx @@ -2,9 +2,10 @@ import { render } from "ink-testing-library"; import React from "react"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { getAllTools } from "src/stream/handleToolCalls.js"; + import { SERVICE_NAMES, serviceContainer } from "../../services/index.js"; import { modeService } from "../../services/ModeService.js"; -import { getAllTools } from "../../streamChatResponse.js"; import { createUITestContext } from "../../test-helpers/ui-test-context.js"; import { AppRoot } from "../AppRoot.js"; diff --git a/extensions/cli/src/ui/hooks/useChat.clear.test.ts b/extensions/cli/src/ui/hooks/useChat.clear.test.ts index fe8c2ed8d..70a88a973 100644 --- a/extensions/cli/src/ui/hooks/useChat.clear.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.clear.test.ts @@ -1,7 +1,7 @@ +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; import { ChatCompletionMessageParam } from "openai/resources.mjs"; import { beforeEach, describe, expect, it, vi } from "vitest"; -import { convertToUnifiedHistory } from "../../messageConversion.js"; import { startNewSession } from "../../session.js"; import { processSlashCommandResult } from "./useChat.helpers.js"; diff --git a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts index 13553cbe0..6997a4c4b 100644 --- a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts @@ -1,6 +1,6 @@ import type { ChatHistoryItem } from "core/index.js"; +import { convertToUnifiedHistory } from "core/util/messageConversion.js"; -import { convertToUnifiedHistory } from "../../messageConversion.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { logger } from "../../util/logger.js"; diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index d6d1ecc4b..d8b15aab3 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -219,7 +219,9 @@ export async function executeStreaming({ currentCompactionIndex, }: ExecuteStreamingOptions): Promise { const { getHistoryForLLM } = await import("../../compaction.js"); - const { streamChatResponse } = await import("../../streamChatResponse.js"); + const { streamChatResponse } = await import( + "../../stream/streamChatResponse.js" + ); if (model && llmApi) { if ( From 4d3b2f19ed875d380524f574cc443d2e72b3827d Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 21:42:39 -0700 Subject: [PATCH 22/25] fix: linting and address feedback --- .../cli/src/compaction.infiniteLoop.test.ts | 2 +- extensions/cli/src/compaction.test.ts | 2 +- extensions/cli/src/constants/session.ts | 4 ++++ extensions/cli/src/session.ts | 13 +++++++------ .../streamChatResponse.autoCompaction.test.ts | 19 +++++++++++-------- .../cli/src/ui/hooks/useChat.clear.test.ts | 3 +++ .../cli/src/ui/hooks/useChat.helpers.ts | 3 ++- extensions/cli/vitest.setup.ts | 3 +++ 8 files changed, 32 insertions(+), 17 deletions(-) create mode 100644 extensions/cli/src/constants/session.ts diff --git a/extensions/cli/src/compaction.infiniteLoop.test.ts b/extensions/cli/src/compaction.infiniteLoop.test.ts index 14ac4d862..a1e383669 100644 --- a/extensions/cli/src/compaction.infiniteLoop.test.ts +++ b/extensions/cli/src/compaction.infiniteLoop.test.ts @@ -7,7 +7,7 @@ import { compactChatHistory } from "./compaction.js"; import { streamChatResponse } from "./stream/streamChatResponse.js"; // Mock the dependencies -vi.mock("./streamChatResponse.js", () => ({ +vi.mock("./stream/streamChatResponse.js", () => ({ streamChatResponse: vi.fn(), })); diff --git a/extensions/cli/src/compaction.test.ts b/extensions/cli/src/compaction.test.ts index 394d26893..fd561ed23 100644 --- a/extensions/cli/src/compaction.test.ts +++ b/extensions/cli/src/compaction.test.ts @@ -12,7 +12,7 @@ import { import { streamChatResponse } from "./stream/streamChatResponse.js"; // Mock the streamChatResponse function -vi.mock("./streamChatResponse.js", () => ({ +vi.mock("./stream/streamChatResponse.js", () => ({ streamChatResponse: vi.fn(), })); diff --git a/extensions/cli/src/constants/session.ts b/extensions/cli/src/constants/session.ts new file mode 100644 index 000000000..50ba1d85f --- /dev/null +++ b/extensions/cli/src/constants/session.ts @@ -0,0 +1,4 @@ +/** + * Session-related constants + */ +export const DEFAULT_SESSION_TITLE = "Untitled Session"; diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index cf94dc829..369c2036a 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -6,11 +6,12 @@ import type { ChatHistoryItem, Session, SessionMetadata } from "core/index.js"; import historyManager from "core/util/history.js"; import { v4 as uuidv4 } from "uuid"; +import { DEFAULT_SESSION_TITLE } from "./constants/session.js"; +import { logger } from "./util/logger.js"; + // Re-export SessionMetadata for external consumers export type { SessionMetadata }; -import { logger } from "./util/logger.js"; - // Note: We now use UUID-based session IDs instead of terminal-based IDs. // Each new chat session gets a unique UUID. // The --resume flag loads the most recent session. @@ -69,7 +70,7 @@ class SessionManager { if (!this.currentSession) { this.currentSession = { sessionId: uuidv4(), - title: "Untitled Session", + title: DEFAULT_SESSION_TITLE, workspaceDirectory: process.cwd(), history: [], }; @@ -187,7 +188,7 @@ export function loadSession(): Session | null { export function createSession(history: ChatHistoryItem[] = []): Session { const session: Session = { sessionId: uuidv4(), - title: "Untitled Session", + title: DEFAULT_SESSION_TITLE, workspaceDirectory: process.cwd(), history, }; @@ -265,7 +266,7 @@ function getSessionMetadataWithPreview( return { sessionId: sessionData.sessionId, - title: sessionData.title || "Untitled Session", + title: sessionData.title || DEFAULT_SESSION_TITLE, dateCreated: stats.birthtime.toISOString(), workspaceDirectory: sessionData.workspaceDirectory || "", firstUserMessage, @@ -360,7 +361,7 @@ export function startNewSession(history: ChatHistoryItem[] = []): Session { // Create a new session with a new sessionId const newSession: Session = { sessionId: uuidv4(), - title: "Untitled Session", + title: DEFAULT_SESSION_TITLE, workspaceDirectory: process.cwd(), history, }; diff --git a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts index b3f550e1d..5960a952a 100644 --- a/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts +++ b/extensions/cli/src/stream/streamChatResponse.autoCompaction.test.ts @@ -5,11 +5,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { handleAutoCompaction } from "./streamChatResponse.autoCompaction.js"; // Mock dependencies -vi.mock("./compaction.js", () => ({ +vi.mock("../compaction.js", () => ({ compactChatHistory: vi.fn(), })); -vi.mock("./session.js", () => ({ +vi.mock("../session.js", () => ({ createSession: vi.fn((history) => ({ sessionId: "test", title: "Test", @@ -20,16 +20,16 @@ vi.mock("./session.js", () => ({ updateSessionHistory: vi.fn(), })); -vi.mock("./util/tokenizer.js", () => ({ +vi.mock("../util/tokenizer.js", () => ({ shouldAutoCompact: vi.fn(), getAutoCompactMessage: vi.fn(), })); -vi.mock("./util/formatError.js", () => ({ +vi.mock("../util/formatError.js", () => ({ formatError: vi.fn((error) => error.message || String(error)), })); -vi.mock("./util/logger.js", () => ({ +vi.mock("../util/logger.js", () => ({ logger: { info: vi.fn(), debug: vi.fn(), @@ -70,7 +70,8 @@ describe("handleAutoCompaction", () => { it("should return original history when auto-compaction is not needed", async () => { const { shouldAutoCompact } = await import("../util/tokenizer.js"); - vi.mocked(shouldAutoCompact).mockReturnValue(false); + const mockedShouldAutoCompact = shouldAutoCompact as any; + mockedShouldAutoCompact.mockReturnValue(false); const result = await handleAutoCompaction( mockChatHistory, @@ -113,7 +114,8 @@ describe("handleAutoCompaction", () => { compactionContent: "Conversation summary...", }; - vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); + const mockedCompactChatHistory = compactChatHistory as any; + mockedCompactChatHistory.mockResolvedValue(mockCompactionResult); const mockCallbacks = { onSystemMessage: vi.fn(), @@ -215,7 +217,8 @@ describe("handleAutoCompaction", () => { compactionContent: "Summary", }; - vi.mocked(compactChatHistory).mockResolvedValue(mockCompactionResult); + const mockedCompactChatHistory = compactChatHistory as any; + mockedCompactChatHistory.mockResolvedValue(mockCompactionResult); const mockCallbacks = { onSystemMessage: vi.fn(), diff --git a/extensions/cli/src/ui/hooks/useChat.clear.test.ts b/extensions/cli/src/ui/hooks/useChat.clear.test.ts index 70a88a973..1c0a7341e 100644 --- a/extensions/cli/src/ui/hooks/useChat.clear.test.ts +++ b/extensions/cli/src/ui/hooks/useChat.clear.test.ts @@ -19,6 +19,9 @@ describe("useChat clear command", () => { let mockOnClear: ReturnType; beforeEach(() => { + // Clear all mocks to prevent call history leaking between tests + vi.clearAllMocks(); + mockSetChatHistory = vi.fn(); mockExit = vi.fn(); mockOnClear = vi.fn(); diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 3d3b25622..21a1b63b6 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -5,6 +5,7 @@ import { getLastNPathParts } from "core/util/uri.js"; import { v4 as uuidv4 } from "uuid"; import { compactChatHistory } from "../../compaction.js"; +import { DEFAULT_SESSION_TITLE } from "../../constants/session.js"; import { loadSession, updateSessionHistory, @@ -422,7 +423,7 @@ export async function generateSessionTitle( currentSessionTitle?: string, ): Promise { // Only generate title for untitled sessions - if (currentSessionTitle && currentSessionTitle !== "Untitled Session") { + if (currentSessionTitle && currentSessionTitle !== DEFAULT_SESSION_TITLE) { return undefined; } diff --git a/extensions/cli/vitest.setup.ts b/extensions/cli/vitest.setup.ts index 886bd6ca0..d94470c02 100644 --- a/extensions/cli/vitest.setup.ts +++ b/extensions/cli/vitest.setup.ts @@ -19,6 +19,9 @@ vi.mock("./src/systemMessage.js", () => ({ ), })); +// Mock environment for tests +process.env.CONTINUE_GLOBAL_DIR = "/tmp/continue-test"; + // Set up global afterEach hook to clear all timers and reset console afterEach(() => { // Clear vitest timers From 71403237f38dc219e8fca98cea776ad36be3429f Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 22:08:24 -0700 Subject: [PATCH 23/25] fix tsts --- extensions/cli/src/e2e/auth.test.ts | 22 +++++++++++++++++++--- extensions/cli/src/e2e/resume-flag.test.ts | 21 +++++++++++++++++++++ extensions/cli/src/services/index.ts | 2 +- extensions/cli/src/session.ts | 12 +++++++++--- 4 files changed, 50 insertions(+), 7 deletions(-) diff --git a/extensions/cli/src/e2e/auth.test.ts b/extensions/cli/src/e2e/auth.test.ts index 79f9352c5..e102cc0f6 100644 --- a/extensions/cli/src/e2e/auth.test.ts +++ b/extensions/cli/src/e2e/auth.test.ts @@ -29,13 +29,23 @@ describe("E2E: Authentication", () => { await fs.writeFile( authPath, JSON.stringify({ + userId: "test-user", + userEmail: "test@example.com", accessToken: "test-token", - user: { id: "test-user", email: "test@example.com" }, + refreshToken: "test-refresh-token", + expiresAt: Date.now() + 3600000, + organizationId: null, }), ); // Run logout - const result = await runCLI(context, { args: ["logout"] }); + const result = await runCLI(context, { + args: ["logout"], + env: { + HOME: context.testDir, + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue") + } + }); expect(result.exitCode).toBe(0); expect(result.stdout).toContain("Successfully logged out"); @@ -49,7 +59,13 @@ describe("E2E: Authentication", () => { }); it("should handle logout when not logged in", async () => { - const result = await runCLI(context, { args: ["logout"] }); + const result = await runCLI(context, { + args: ["logout"], + env: { + HOME: context.testDir, + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue") + } + }); expect(result.exitCode).toBe(0); expect(result.stdout).toContain("No active session found"); diff --git a/extensions/cli/src/e2e/resume-flag.test.ts b/extensions/cli/src/e2e/resume-flag.test.ts index a6d29da27..591b1d94e 100644 --- a/extensions/cli/src/e2e/resume-flag.test.ts +++ b/extensions/cli/src/e2e/resume-flag.test.ts @@ -35,6 +35,7 @@ describe("E2E: Resume Flag", () => { env: { // Use a fixed session ID so both CLI calls use the same session CONTINUE_CLI_TEST_SESSION_ID: "test-session-123", + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), }, timeout: 15000, }); @@ -45,6 +46,14 @@ describe("E2E: Resume Flag", () => { // Verify that a session file was created const sessionDir = path.join(context.testDir, ".continue", "sessions"); + + // Ensure session directory exists + try { + await fs.mkdir(sessionDir, { recursive: true }); + } catch (error) { + // Directory already exists, continue + } + const sessionFiles = (await fs.readdir(sessionDir)).filter( f => f.endsWith('.json') && f !== 'sessions.json' ); @@ -75,6 +84,7 @@ describe("E2E: Resume Flag", () => { args: ["--resume", "--config", context.configPath], env: { CONTINUE_CLI_TEST_SESSION_ID: "test-session-123", + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), }, timeout: 15000, }); @@ -92,6 +102,7 @@ describe("E2E: Resume Flag", () => { args: ["--resume", "--config", context.configPath], env: { CONTINUE_CLI_TEST_SESSION_ID: "no-session-456", + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), }, timeout: 15000, }); @@ -129,6 +140,7 @@ describe("E2E: Resume Flag", () => { args: ["-p", "--config", context.configPath, "first message"], env: { CONTINUE_CLI_TEST_SESSION_ID: sessionId, + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), }, timeout: 15000, }); @@ -138,6 +150,14 @@ describe("E2E: Resume Flag", () => { // Verify the first session was saved correctly const sessionDir = path.join(context.testDir, ".continue", "sessions"); + + // Ensure session directory exists + try { + await fs.mkdir(sessionDir, { recursive: true }); + } catch (error) { + // Directory already exists, continue + } + let sessionFiles = (await fs.readdir(sessionDir)).filter( f => f.endsWith('.json') && f !== 'sessions.json' ); @@ -159,6 +179,7 @@ describe("E2E: Resume Flag", () => { ], env: { CONTINUE_CLI_TEST_SESSION_ID: sessionId, + CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue"), }, timeout: 15000, }); diff --git a/extensions/cli/src/services/index.ts b/extensions/cli/src/services/index.ts index 0f9bc65cc..e9409c722 100644 --- a/extensions/cli/src/services/index.ts +++ b/extensions/cli/src/services/index.ts @@ -118,7 +118,7 @@ export async function initializeServices( () => systemMessageService.initialize({ additionalRules: commandOptions.rule, - format: undefined, // format is not part of BaseCommandOptions + format: (commandOptions as any).format, // format option from CLI headless: initOptions.headless, }), [], // No dependencies diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index 369c2036a..1b2d17880 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -32,8 +32,9 @@ function getSessionDir(): string { return sessionDir; } - const homeDir = os.homedir(); - const sessionDir = path.join(homeDir, ".continue", "sessions"); + // Use CONTINUE_GLOBAL_DIR if set (for testing) + const continueHome = process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"); + const sessionDir = path.join(continueHome, "sessions"); // Create directory if it doesn't exist if (!fs.existsSync(sessionDir)) { @@ -68,8 +69,13 @@ class SessionManager { getCurrentSession(): Session { if (!this.currentSession) { + // Use test session ID for testing consistency + const sessionId = process.env.CONTINUE_CLI_TEST_SESSION_ID ? + process.env.CONTINUE_CLI_TEST_SESSION_ID : + uuidv4(); + this.currentSession = { - sessionId: uuidv4(), + sessionId, title: DEFAULT_SESSION_TITLE, workspaceDirectory: process.cwd(), history: [], From fcaa80f4453b641eddb8779e1816c0cf2480dc6e Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 22:16:05 -0700 Subject: [PATCH 24/25] fix: lint, etc --- core/util/history.test.ts | 6 ++++-- core/util/messageConversion.ts | 11 +++++++---- extensions/cli/src/session.ts | 11 ++++++----- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/core/util/history.test.ts b/core/util/history.test.ts index dbcf69619..632bd7836 100644 --- a/core/util/history.test.ts +++ b/core/util/history.test.ts @@ -93,8 +93,9 @@ describe("Many sessions created", () => { const offset = 10; const sessions = historyManager.list({ offset: offset, limit: limit }); + // Sessions are now reversed, so newest (99) comes first const sessionIds = Array.from({ length: limit }, (_, i) => - (i + offset).toString(), + (99 - offset - i).toString(), ); const isSessionIdInList = (sessionId: string) => sessions.some((session) => session.sessionId === sessionId); @@ -105,7 +106,8 @@ describe("Many sessions created", () => { const limit = 25; const sessions = historyManager.list({ limit: limit }); - const sessionIds = Array.from({ length: limit }, (_, i) => i.toString()); + // Sessions are now reversed, so newest (99) comes first + const sessionIds = Array.from({ length: limit }, (_, i) => (99 - i).toString()); const isSessionIdInList = (sessionId: string) => sessions.some((session) => session.sessionId === sessionId); diff --git a/core/util/messageConversion.ts b/core/util/messageConversion.ts index cc561cb84..b94d7e63f 100644 --- a/core/util/messageConversion.ts +++ b/core/util/messageConversion.ts @@ -222,10 +222,13 @@ function handleToolResult( if (!toolCall) return; // Add tool result as context to the previous assistant message - const lastAssistantIndex = historyItems.findLastIndex( - (item) => item.message.role === "assistant", - ); - + let lastAssistantIndex = -1; + for (let i = historyItems.length - 1; i >= 0; i--) { + if (historyItems[i].message.role === "assistant") { + lastAssistantIndex = i; + break; + } + } if (lastAssistantIndex < 0) return; if (!historyItems[lastAssistantIndex].toolCallStates) return; diff --git a/extensions/cli/src/session.ts b/extensions/cli/src/session.ts index 1b2d17880..b6752d617 100644 --- a/extensions/cli/src/session.ts +++ b/extensions/cli/src/session.ts @@ -33,7 +33,8 @@ function getSessionDir(): string { } // Use CONTINUE_GLOBAL_DIR if set (for testing) - const continueHome = process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"); + const continueHome = + process.env.CONTINUE_GLOBAL_DIR || path.join(os.homedir(), ".continue"); const sessionDir = path.join(continueHome, "sessions"); // Create directory if it doesn't exist @@ -70,10 +71,10 @@ class SessionManager { getCurrentSession(): Session { if (!this.currentSession) { // Use test session ID for testing consistency - const sessionId = process.env.CONTINUE_CLI_TEST_SESSION_ID ? - process.env.CONTINUE_CLI_TEST_SESSION_ID : - uuidv4(); - + const sessionId = process.env.CONTINUE_CLI_TEST_SESSION_ID + ? process.env.CONTINUE_CLI_TEST_SESSION_ID + : uuidv4(); + this.currentSession = { sessionId, title: DEFAULT_SESSION_TITLE, From ddea11daf9fe26bf0a93df18c80997beeb50de50 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 27 Aug 2025 22:16:58 -0700 Subject: [PATCH 25/25] chore: format --- core/util/history.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/core/util/history.test.ts b/core/util/history.test.ts index 632bd7836..b27a09a4f 100644 --- a/core/util/history.test.ts +++ b/core/util/history.test.ts @@ -107,7 +107,9 @@ describe("Many sessions created", () => { const sessions = historyManager.list({ limit: limit }); // Sessions are now reversed, so newest (99) comes first - const sessionIds = Array.from({ length: limit }, (_, i) => (99 - i).toString()); + const sessionIds = Array.from({ length: limit }, (_, i) => + (99 - i).toString(), + ); const isSessionIdInList = (sessionId: string) => sessions.some((session) => session.sessionId === sessionId);