diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts index 5a7d8c440..7371ed510 100644 --- a/extensions/cli/src/commands/serve.helpers.ts +++ b/extensions/cli/src/commands/serve.helpers.ts @@ -60,7 +60,7 @@ export async function streamChatResponseWithInterruption( } // Always create a new assistant message for each tool call - const toolCallId = `tool_${Date.now()}`; + const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; const toolCallState: ToolCallState = { toolCallId: toolCallId, toolCall: { @@ -152,7 +152,7 @@ export async function streamChatResponseWithInterruption( state.session.history.push({ message: { role: "system", - content: `⚠️ Tool ${toolName} requires permission`, + content: `WARNING: Tool ${toolName} requires permission`, }, contextItems: [], }); diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index 8a68f4027..48e9a6478 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -4,6 +4,7 @@ import { promisify } from "util"; import chalk from "chalk"; import express, { Request, Response } from "express"; +import type { ChatHistoryItem } from "../../../../core/index.js"; import { getAssistantSlug } from "../auth/workos.js"; import { processCommandFlags } from "../flags/flagProcessor.js"; import { convertFromUnifiedHistory } from "../messageConversion.js"; @@ -112,7 +113,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { true, ); - const initialHistory = []; + const initialHistory: ChatHistoryItem[] = []; if (systemMessage) { initialHistory.push({ message: { role: "system" as const, content: systemMessage }, diff --git a/extensions/cli/src/compaction.pruneLastMessage.test.ts b/extensions/cli/src/compaction.pruneLastMessage.test.ts index fee7f3347..1152837e8 100644 --- a/extensions/cli/src/compaction.pruneLastMessage.test.ts +++ b/extensions/cli/src/compaction.pruneLastMessage.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect } from "vitest"; import { pruneLastMessage } from "./compaction.js"; import { convertToUnifiedHistory } from "./messageConversion.js"; +import { logger } from "./util/logger.js"; describe("pruneLastMessage", () => { it("should return empty array for empty input", () => { @@ -76,10 +77,10 @@ describe("pruneLastMessage", () => { // The test data will be converted differently by the message converter // Since assistant message with tool_calls gets combined with tool result // We need to check what actually gets generated - console.log("Converted history:", JSON.stringify(history, null, 2)); + logger.debug("Converted history:", { history }); const result = pruneLastMessage(history); - console.log("Pruned result:", JSON.stringify(result, null, 2)); + logger.debug("Pruned result:", { result }); // For now, just check that it returns the expected structure expect(result).toEqual([ @@ -142,12 +143,12 @@ describe("pruneLastMessage", () => { const result = pruneLastMessage(history); // Check what we actually got - console.log("Result length:", result.length); + logger.debug("Result length:", { length: result.length }); if (result.length > 0) { - console.log("First item role:", result[0].message.role); + logger.debug("First item role:", { role: result[0].message.role }); } if (result.length > 1) { - console.log("Second item role:", result[1].message.role); + logger.debug("Second item role:", { role: result[1].message.role }); } // Adjust based on actual behavior diff --git a/extensions/cli/src/messageConversion.test.ts b/extensions/cli/src/messageConversion.test.ts index d778a13d4..b3691108c 100644 --- a/extensions/cli/src/messageConversion.test.ts +++ b/extensions/cli/src/messageConversion.test.ts @@ -1,4 +1,5 @@ import type { ChatHistoryItem } from "../../../core/index.js"; + import { convertFromUnifiedHistory } from "./messageConversion.js"; describe("convertFromUnifiedHistory", () => { @@ -32,7 +33,8 @@ describe("convertFromUnifiedHistory", () => { expect(result).toHaveLength(1); expect(result[0]).toEqual({ role: "user", - content: "Please review @test-file.txt\n\n\nconsole.log('Hello, world!');\n", + content: + "Please review @test-file.txt\n\n\nconsole.log('Hello, world!');\n", }); }); @@ -99,7 +101,8 @@ describe("convertFromUnifiedHistory", () => { expect(result).toHaveLength(1); expect(result[0]).toEqual({ role: "user", - content: "Compare @file1.js and @file2.js\n\n\nconst a = 1;\n\n\n\nconst b = 2;\n", + content: + 'Compare @file1.js and @file2.js\n\n\nconst a = 1;\n\n\n\nconst b = 2;\n', }); }); @@ -136,4 +139,4 @@ describe("convertFromUnifiedHistory", () => { content: "Here's the analysis", }); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/streamChatResponse.autoCompaction.ts b/extensions/cli/src/streamChatResponse.autoCompaction.ts index 8ec03e251..6b271fa36 100644 --- a/extensions/cli/src/streamChatResponse.autoCompaction.ts +++ b/extensions/cli/src/streamChatResponse.autoCompaction.ts @@ -3,6 +3,8 @@ import { BaseLlmApi } from "@continuedev/openai-adapters"; import type { ChatCompletionMessageParam } from "openai/resources.mjs"; import React from "react"; +import type { ChatHistoryItem } from "../../../core/index.js"; + import { compactChatHistory } from "./compaction.js"; import { convertFromUnifiedHistory, @@ -19,7 +21,7 @@ interface AutoCompactionCallbacks { onContent?: (content: string) => void; // For TUI mode - setMessages?: React.Dispatch>; // Generic for compatibility + setMessages?: React.Dispatch>; setChatHistory?: React.Dispatch< React.SetStateAction >; @@ -72,12 +74,14 @@ function handleCompactionSuccess( ) { callbacks.setChatHistory(result.compactedHistory); callbacks.setCompactionIndex(result.compactionIndex); - callbacks.setMessages((prev: any) => [ + callbacks.setMessages((prev: ChatHistoryItem[]) => [ ...prev, { - role: "system", - content: successMessage, - messageType: "system" as const, + message: { + role: "system", + content: successMessage, + }, + contextItems: [], }, ]); } @@ -101,12 +105,14 @@ function handleCompactionError( if (callbacks?.onSystemMessage) { callbacks.onSystemMessage(warningMessage); } else if (callbacks?.setMessages) { - callbacks.setMessages((prev: any) => [ + callbacks.setMessages((prev: ChatHistoryItem[]) => [ ...prev, { - role: "system", - content: warningMessage, - messageType: "system" as const, + message: { + role: "system", + content: warningMessage, + }, + contextItems: [], }, ]); } diff --git a/extensions/cli/src/ui/ConfigSelector.tsx b/extensions/cli/src/ui/ConfigSelector.tsx index 60cd1c9f2..f47a97b1b 100644 --- a/extensions/cli/src/ui/ConfigSelector.tsx +++ b/extensions/cli/src/ui/ConfigSelector.tsx @@ -81,7 +81,7 @@ const ConfigSelector: React.FC = ({ return assistants.map((assistant) => { const name = (assistant.configResult.config as any)?.name ?? - `${assistant.ownerSlug}/${assistant.configResult.config}`; + `${assistant.ownerSlug}/${assistant.packageSlug}`; const displayName = `[${org.name}] ${name}`; // Create unique ID that includes org info to avoid conflicts const uniqueId = `${org.id || "personal"}-${assistant.packageSlug}`; diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index a75e90337..233a485c7 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -313,17 +313,17 @@ export async function handleAutoCompaction({ currentChatHistory: ChatHistoryItem[]; currentCompactionIndex: number | null; }> { - // Check if auto-compaction is needed - // Convert to legacy format for token counting - const legacyHistory = convertFromUnifiedHistory(chatHistory); - if (!model || !shouldAutoCompact(legacyHistory, model)) { - return { - currentChatHistory: chatHistory, - currentCompactionIndex: _compactionIndex, - }; - } - try { + // Check if auto-compaction is needed + // Convert to legacy format for token counting + const legacyHistory = convertFromUnifiedHistory(chatHistory); + if (!model || !shouldAutoCompact(legacyHistory, model)) { + return { + currentChatHistory: chatHistory, + currentCompactionIndex: _compactionIndex, + }; + } + logger.info("Auto-compaction triggered for TUI mode"); // Add compacting message diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 39b6c914c..2f8e1de84 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -39,7 +39,7 @@ export function createStreamCallbacks( const newHistory = [...prev]; // Always create a new assistant message for each tool call - const toolCallId = `tool_${Date.now()}`; + const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; const toolCallState: ToolCallState = { toolCallId: toolCallId, toolCall: { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 750d0c708..560275a51 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -211,15 +211,19 @@ export function useChat({ currentCompactionIndex, }); - // Save the updated session - logger.debug("Saving session", { historyLength: newHistory.length }); - const updatedSession: Session = { - ...currentSession, - history: newHistory, - }; - saveSession(updatedSession); - setCurrentSession(updatedSession); - logger.debug("Session saved"); + // Save the updated session with the latest chat history that includes the assistant's reply + // The streamCallbacks update setChatHistory during streaming, so we need to get the current state + setChatHistory((currentHistory) => { + logger.debug("Saving session", { historyLength: currentHistory.length }); + const updatedSession: Session = { + ...currentSession, + history: currentHistory, + }; + saveSession(updatedSession); + setCurrentSession(updatedSession); + logger.debug("Session saved"); + return currentHistory; + }); } catch (error: any) { const errorMessage = `Error: ${formatError(error)}`; setChatHistory((prev) => [ diff --git a/extensions/cli/src/ui/hooks/useMessageRenderer.tsx b/extensions/cli/src/ui/hooks/useMessageRenderer.tsx index e89d92fba..decd466fe 100644 --- a/extensions/cli/src/ui/hooks/useMessageRenderer.tsx +++ b/extensions/cli/src/ui/hooks/useMessageRenderer.tsx @@ -5,7 +5,19 @@ import { MemoizedMessage } from "../components/MemoizedMessage.js"; export function useMessageRenderer() { const renderMessage = useCallback((item: ChatHistoryItem, index: number) => { - return ; + // Generate a unique key by combining message role, content hash, and timestamp + // This provides a stable identifier that won't change during re-renders + const messageContent = typeof item.message.content === 'string' + ? item.message.content + : JSON.stringify(item.message.content); + + const toolCallsKey = item.toolCallStates + ? item.toolCallStates.map(tc => tc.toolCallId).join('-') + : ''; + + const uniqueKey = `${item.message.role}-${messageContent.slice(0, 50)}-${toolCallsKey}-${index}`; + + return ; }, []); return { renderMessage }; diff --git a/extensions/cli/validate-aliases.mjs b/extensions/cli/validate-aliases.mjs index 02273cb68..f22878894 100755 --- a/extensions/cli/validate-aliases.mjs +++ b/extensions/cli/validate-aliases.mjs @@ -4,6 +4,21 @@ import { existsSync, readFileSync } from "fs"; import { dirname, resolve } from "path"; import { fileURLToPath } from "url"; +// Import CLI logger for consistent logging +let logger; +try { + // Try to import the compiled logger + const loggerModule = await import('./dist/util/logger.js'); + logger = loggerModule.logger; +} catch { + // Fallback to console if logger not available (e.g., not built yet) + logger = { + info: console.log, + warn: console.warn, + error: console.error + }; +} + const __dirname = dirname(fileURLToPath(import.meta.url)); // Colors for output @@ -25,7 +40,7 @@ function getDefinedAliases() { // Find the alias object in the build file const aliasMatch = buildContent.match(/alias:\s*{([^}]+)}/s); if (!aliasMatch) { - console.warn( + logger.warn( `${colors.yellow}Warning: No aliases found in build.mjs${colors.reset}`, ); return new Set(); @@ -104,7 +119,7 @@ function findLocalPackages(startPath, visited = new Set()) { } } } catch (error) { - console.error( + logger.error( `${colors.red}Error reading ${packageJsonPath}: ${error.message}${colors.reset}`, ); } @@ -120,7 +135,7 @@ function findLocalPackages(startPath, visited = new Set()) { * Main validation function */ function validateAliases() { - console.log( + logger.info( `${colors.blue}🔍 Validating esbuild aliases...${colors.reset}\n`, ); @@ -159,51 +174,51 @@ function validateAliases() { // Report results if (missingAliases.length > 0) { - console.log( + logger.error( `${colors.red}❌ Missing aliases (WILL CAUSE RUNTIME ERRORS):${colors.reset}`, ); missingAliases.forEach((pkg) => { - console.log(` ✗ ${pkg}`); + logger.error(` ✗ ${pkg}`); }); - console.log(); - console.log( + logger.error(""); + logger.error( `${colors.red}Add these to the alias section in build.mjs:${colors.reset}`, ); missingAliases.forEach((pkg) => { const packageName = pkg.replace("@continuedev/", "").replace(/-/g, "_"); - console.log( + logger.error( ` "${pkg}": resolve(__dirname, "../../packages/${pkg.replace("@continuedev/", "")}/dist/index.js"),`, ); }); - console.log(); + logger.error(""); } if (unnecessaryAliases.length > 0) { - console.log( + logger.warn( `${colors.yellow}⚠️ Potentially unnecessary aliases:${colors.reset}`, ); unnecessaryAliases.forEach((alias) => { - console.log(` ? ${alias}`); + logger.warn(` ? ${alias}`); }); - console.log(); + logger.warn(""); } // Exit with appropriate code if (missingAliases.length > 0) { - console.log( + logger.error( `${colors.red}✗ Validation failed! Missing ${missingAliases.length} required alias(es).${colors.reset}`, ); - console.log( + logger.error( `${colors.red}This would cause runtime errors in the bundled CLI.${colors.reset}`, ); process.exit(1); } else if (unnecessaryAliases.length > 0) { - console.log( + logger.warn( `${colors.yellow}✓ Validation passed with warnings.${colors.reset}`, ); process.exit(0); } else { - console.log( + logger.info( `${colors.green}✅ All aliases are correctly configured!${colors.reset}`, ); process.exit(0);