From 749f337ea4b3d678f2fad1debb54fe2d1ae88006 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 1 Sep 2025 13:05:18 -0700 Subject: [PATCH] follow up fixes --- extensions/cli/src/commands/chat.ts | 83 ++++++------- extensions/cli/src/compaction.ts | 2 +- .../cli/src/services/ChatHistoryService.ts | 56 ++++++--- extensions/cli/src/stream/handleToolCalls.ts | 18 +-- .../cli/src/ui/hooks/useChat.helpers.ts | 2 +- .../src/ui/hooks/useChat.remote.helpers.ts | 112 +++++------------- .../src/ui/hooks/useChat.stream.helpers.ts | 35 +++--- extensions/cli/src/ui/hooks/useChat.ts | 2 - extensions/cli/src/ui/types.ts | 2 - 9 files changed, 133 insertions(+), 179 deletions(-) delete mode 100644 extensions/cli/src/ui/types.ts diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index c62b656c4..64ae45dd0 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -14,7 +14,7 @@ import { safeStdout } from "../init.js"; import { configureLogger } from "../logger.js"; import * as logging from "../logging.js"; import { sentryService } from "../sentry.js"; -import { initializeServices } from "../services/index.js"; +import { initializeServices, services } from "../services/index.js"; import { serviceContainer } from "../services/ServiceContainer.js"; import { ModelServiceState, SERVICE_NAMES } from "../services/types.js"; import { @@ -115,14 +115,15 @@ async function handleManualCompaction( } try { - const result = await compactChatHistory(chatHistory, model, llmApi); + const current = services.chatHistory.getHistory(); + const result = await compactChatHistory(current, model, llmApi); - // Replace chat history with compacted version - chatHistory.length = 0; - chatHistory.push(...result.compactedHistory); - - // Save the compacted session - updateSessionHistory(chatHistory); + // Update service-driven history and persist session + services.chatHistory.compact( + result.compactedHistory, + result.compactionIndex, + ); + updateSessionHistory(result.compactedHistory); if (isHeadless) { safeStdout( @@ -210,15 +211,19 @@ async function handleAutoCompaction( }, }; - const result = await coreAutoCompaction(chatHistory, model, llmApi, { - isHeadless, - format, - callbacks, - }); + const result = await coreAutoCompaction( + services.chatHistory.getHistory(), + model, + llmApi, + { + isHeadless, + format, + callbacks, + }, + ); - // Update the original array reference for headless mode - chatHistory.length = 0; - chatHistory.push(...result.chatHistory); + // Update service-driven history + services.chatHistory.setHistory(result.chatHistory); return result.compactionIndex; } @@ -286,7 +291,7 @@ async function processMessage( telemetryService.logUserPrompt(userInput.length, userInput); // Check if auto-compacting is needed BEFORE adding user message - if (shouldAutoCompact(chatHistory, model)) { + if (shouldAutoCompact(services.chatHistory.getHistory(), model)) { const newIndex = await handleAutoCompaction( chatHistory, model, @@ -296,17 +301,12 @@ async function processMessage( ); if (newIndex !== null) { compactionIndex = newIndex; - // Replace chatHistory with compacted version - chatHistory.length = 0; - chatHistory.push(...chatHistory); + // Service already updated in handleAutoCompaction via setHistory } } // Add user message to history AFTER potential compaction - chatHistory.push({ - message: { role: "user", content: userInput }, - contextItems: [], - }); + services.chatHistory.addUserMessage(userInput); // Get AI response with potential tool usage if (!isHeadless) { @@ -316,12 +316,13 @@ async function processMessage( try { const abortController = new AbortController(); - // Handle compaction properly - streamChatResponse modifies the array in place + // Service-driven streaming; history updates occur via ChatHistoryService let finalResponse; if (compactionIndex !== null && compactionIndex !== undefined) { - // When using compaction, we need to send a subset but capture the full history - const historyForLLM = getHistoryForLLM(chatHistory, compactionIndex); - const originalLength = historyForLLM.length; + // Use service to compute history for LLM + const historyForLLM = services.chatHistory.getHistoryForLLM( + compactionIndex, + ); finalResponse = await streamChatResponse( historyForLLM, @@ -329,19 +330,14 @@ async function processMessage( llmApi, abortController, ); - - // Append any new messages (assistant/tool) that were added by streamChatResponse - const newMessages = historyForLLM.slice(originalLength); - chatHistory.push(...newMessages); } else { - // No compaction - just pass the full history directly + // No compaction - get full history from service finalResponse = await streamChatResponse( - chatHistory, + services.chatHistory.getHistory(), model, llmApi, abortController, ); - // No need to sync back - streamChatResponse modifies chatHistory in place } // Generate session title after first assistant response @@ -368,7 +364,7 @@ async function processMessage( } // Save session after each successful response - updateSessionHistory(chatHistory); + updateSessionHistory(services.chatHistory.getHistory()); } catch (e: any) { const error = e instanceof Error ? e : new Error(String(e)); @@ -381,11 +377,17 @@ async function processMessage( sentryService.captureException(error, { context: "chat_response", isHeadless, - chatHistoryLength: chatHistory.length, + chatHistoryLength: services.chatHistory.getHistory().length, }); if (!isHeadless) { logger.info( - chalk.dim(`Chat history:\n${JSON.stringify(chatHistory, null, 2)}`), + chalk.dim( + `Chat history:\n${JSON.stringify( + services.chatHistory.getHistory(), + null, + 2, + )}`, + ), ); } } @@ -414,12 +416,11 @@ async function runHeadlessMode( throw new Error("No models were found."); } - // Initialize chat history + // Initialize service-driven history (resume if requested) const chatHistory = await initializeChatHistory(options); - - // Track compaction index if resuming with compacted history let compactionIndex: number | null = null; if (options.resume) { + services.chatHistory.setHistory(chatHistory); compactionIndex = findCompactionIndex(chatHistory); } diff --git a/extensions/cli/src/compaction.ts b/extensions/cli/src/compaction.ts index 3edbe0260..8513b1405 100644 --- a/extensions/cli/src/compaction.ts +++ b/extensions/cli/src/compaction.ts @@ -80,7 +80,7 @@ export async function compactChatHistory( historyForCompaction = [...historyToUse, compactionPrompt]; } - // Stream the compaction response + // Stream the compaction response (service drives updates; this collects content locally) const controller = new AbortController(); let compactionContent = ""; diff --git a/extensions/cli/src/services/ChatHistoryService.ts b/extensions/cli/src/services/ChatHistoryService.ts index 2e8e3d799..7dc92b56a 100644 --- a/extensions/cli/src/services/ChatHistoryService.ts +++ b/extensions/cli/src/services/ChatHistoryService.ts @@ -109,21 +109,47 @@ export class ChatHistoryService extends BaseService { message.toolCalls = toolCalls; } - const toolCallStates = toolCalls?.map((tc) => ({ - toolCallId: tc.id, - toolCall: { - id: tc.id, - type: "function" as const, - function: { - name: tc.name || tc.function?.name, - arguments: typeof tc.arguments === "string" - ? tc.arguments - : JSON.stringify(tc.arguments || tc.function?.arguments || {}), + const toolCallStates = toolCalls?.map((tc) => { + const id = tc.id; + const name = tc.function?.name ?? tc.name; + // Prefer explicit string arguments; otherwise stringify object arguments + const rawArgStr = + typeof tc.arguments === "string" + ? tc.arguments + : typeof tc.function?.arguments === "string" + ? tc.function.arguments + : tc.arguments !== undefined + ? JSON.stringify(tc.arguments) + : tc.function?.arguments !== undefined + ? String(tc.function.arguments) + : "{}"; + + // parsedArgs: prefer object, else parse the string if possible + let parsedArgs: any = {}; + if (tc && typeof tc.arguments === "object" && tc.arguments !== null) { + parsedArgs = tc.arguments; + } else if (typeof rawArgStr === "string") { + try { + parsedArgs = JSON.parse(rawArgStr); + } catch { + parsedArgs = {}; + } + } + + return { + toolCallId: id, + toolCall: { + id, + type: "function" as const, + function: { + name, + arguments: rawArgStr, + }, }, - }, - status: "generated" as ToolStatus, - parsedArgs: typeof tc.arguments === "object" ? tc.arguments : {}, - })); + status: "generated" as ToolStatus, + parsedArgs, + }; + }); const newMessage = createHistoryItem(message, [], toolCallStates); const newHistory = [...this.currentState.history, newMessage]; @@ -165,7 +191,7 @@ export class ChatHistoryService extends BaseService { } /** - * Add a generic history item (for compatibility during migration) + * Add a generic history item */ addHistoryItem(item: ChatHistoryItem): ChatHistoryItem { const newHistory = [...this.currentState.history, item]; diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts index 5c0ac53d5..982d4cb89 100644 --- a/extensions/cli/src/stream/handleToolCalls.ts +++ b/extensions/cli/src/stream/handleToolCalls.ts @@ -33,22 +33,8 @@ export async function handleToolCalls( if (toolCalls.length === 0) { if (content) { if (useService) { - // Service-driven: rely solely on service state (no local mutations) - try { - const svcHistory = chatHistorySvc.getHistory(); - const svcLast = svcHistory[svcHistory.length - 1]; - const isDuplicateSvc = - !!svcLast && - svcLast.message.role === "assistant" && - typeof svcLast.message.content === "string" && - svcLast.message.content === content && - !(svcLast as any).toolCallStates?.length; - if (!isDuplicateSvc) { - chatHistorySvc.addAssistantMessage(content); - } - } catch { - chatHistorySvc.addAssistantMessage(content); - } + // Service-driven: write assistant message via service + chatHistorySvc.addAssistantMessage(content); } else { // Fallback only when service is unavailable chatHistory.push( diff --git a/extensions/cli/src/ui/hooks/useChat.helpers.ts b/extensions/cli/src/ui/hooks/useChat.helpers.ts index 21a1b63b6..f90e3df4c 100644 --- a/extensions/cli/src/ui/hooks/useChat.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.helpers.ts @@ -295,7 +295,7 @@ export async function handleSpecialCommands({ // Handle /exit command in remote mode if (isRemoteMode && remoteUrl && trimmedMessage === "/exit") { const { handleRemoteExit } = await import("./useChat.remote.helpers.js"); - await handleRemoteExit(remoteUrl, setChatHistory, exit); + await handleRemoteExit(remoteUrl, exit); return true; } diff --git a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts index 75beb23ff..fa9551aa6 100644 --- a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts @@ -1,5 +1,6 @@ import type { ChatHistoryItem } from "core/index.js"; +import { services } from "../../services/index.js"; import { posthogService } from "../../telemetry/posthogService.js"; import { logger } from "../../util/logger.js"; @@ -25,7 +26,6 @@ async function pollRemoteServerState( interface SetupRemotePollingOptions { remoteUrl: string; - setChatHistory: React.Dispatch>; setIsWaitingForResponse: React.Dispatch>; responseStartTime: number | null; setResponseStartTime: React.Dispatch>; @@ -36,7 +36,6 @@ interface SetupRemotePollingOptions { */ export function setupRemotePolling({ remoteUrl, - setChatHistory, setIsWaitingForResponse, responseStartTime, setResponseStartTime, @@ -54,7 +53,6 @@ export function setupRemotePolling({ if (state && isMounted) { updateStateFromRemote({ state, - setChatHistory, setIsWaitingForResponse, responseStartTime, setResponseStartTime, @@ -81,7 +79,6 @@ export function setupRemotePolling({ interface UpdateStateFromRemoteOptions { state: RemoteServerState; - setChatHistory: React.Dispatch>; setIsWaitingForResponse: React.Dispatch>; responseStartTime: number | null; setResponseStartTime: React.Dispatch>; @@ -92,37 +89,16 @@ interface UpdateStateFromRemoteOptions { */ function updateStateFromRemote({ state, - setChatHistory, setIsWaitingForResponse, responseStartTime, setResponseStartTime, }: UpdateStateFromRemoteOptions): void { // Update chat history from server - now using session.history directly if (state.session && state.session.history) { - setChatHistory((prevHistory) => { - // Use session history directly - it already has the correct type - const newHistory = state.session.history; - - // Quick length check first - if (prevHistory.length !== newHistory.length) { - return newHistory; - } - - // Deep comparison - check if content actually changed - const hasChanged = newHistory.some((item, index) => { - const prevItem = prevHistory[index]; - return ( - !prevItem || - prevItem.message.role !== item.message.role || - prevItem.message.content !== item.message.content || - JSON.stringify(prevItem.toolCallStates) !== - JSON.stringify(item.toolCallStates) - ); - }); - - // Only update if there are actual changes - return hasChanged ? newHistory : prevHistory; - }); + const newHistory = state.session.history as ChatHistoryItem[]; + // Let ChatHistoryService own the history and emit updates to UI + services.chatHistory.setRemoteMode(true); + services.chatHistory.setHistory(newHistory); } // Update processing state @@ -139,7 +115,6 @@ function updateStateFromRemote({ */ export async function handleRemoteExit( remoteUrl: string, - setChatHistory: React.Dispatch>, exit: () => void, ): Promise { posthogService.capture("useSlashCommand", { @@ -152,50 +127,34 @@ export async function handleRemoteExit( }); if (response.ok) { - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Remote environment is shutting down...", - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + "Remote environment is shutting down...", + ); + } catch {} setTimeout(() => exit(), 1000); } else { const text = await response.text(); logger.error("Remote shutdown failed:", text); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Failed to shutdown remote environment", - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + "Failed to shutdown remote environment", + ); + } catch {} } } catch (error) { logger.error("Failed to send exit request to remote server:", error); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: "Error: Failed to connect to remote server for shutdown", - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + "Error: Failed to connect to remote server for shutdown", + ); + } catch {} } } interface HandleRemoteMessageOptions { remoteUrl: string; messageContent: string; - setChatHistory: React.Dispatch>; } /** @@ -204,7 +163,6 @@ interface HandleRemoteMessageOptions { export async function handleRemoteMessage({ remoteUrl, messageContent, - setChatHistory, }: HandleRemoteMessageOptions): Promise { try { const response = await fetch(`${remoteUrl}/message`, { @@ -217,29 +175,19 @@ export async function handleRemoteMessage({ if (!response.ok) { const error = await response.json(); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: `Error: ${error.error || "Failed to send message"}`, - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + `Error: ${error.error || "Failed to send message"}`, + ); + } catch {} } // State will be updated by polling } catch (error) { logger.error("Failed to send message to remote server:", error); - setChatHistory((prev) => [ - ...prev, - { - message: { - role: "system", - content: `Error: Failed to connect to remote server`, - }, - contextItems: [], - }, - ]); + try { + services.chatHistory.addSystemMessage( + "Error: Failed to connect to remote server", + ); + } catch {} } } diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index 2f7c42c2f..38d28b3a6 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -24,27 +24,25 @@ export function createStreamCallbacks( onContent: (_: string) => {}, onContentComplete: async (content: string) => { - // Update local React state for UI - setChatHistory((prev) => [ - ...prev, - { - contextItems: [], - message: { - role: "assistant", - content: content, - isStreaming: false, - }, - }, - ]); - - // Also update service; handleToolCalls will de-dup when no tools + // Do not add assistant messages via service; handleToolCalls is the single writer + // For environments where the service isn't ready (unit tests), update local state only try { const svc = services.chatHistory; - if (typeof svc?.isReady === "function" && svc.isReady()) { - svc.addAssistantMessage(content); + const useService = typeof svc?.isReady === "function" && svc.isReady(); + if (!useService && content) { + setChatHistory((prev) => [ + ...prev, + { + contextItems: [], + message: { + role: "assistant", + content: content, + isStreaming: false, + }, + }, + ]); } } catch {} - // Generate session title after first assistant response if (content && llmApi && model) { const currentSession = getCurrentSession(); @@ -273,8 +271,7 @@ export async function executeStreaming({ streamCallbacks, ); - // streamChatResponse modifies the array in place - // The new messages are already in historyForLLM + // Service-driven streaming; history updates occur via ChatHistoryService } else { await streamChatResponse( chatHistory, diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 3fa345f4b..3bdb0c15f 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -160,7 +160,6 @@ export function useChat({ return setupRemotePolling({ remoteUrl, - setChatHistory: setChatHistory, setIsWaitingForResponse, responseStartTime, setResponseStartTime, @@ -389,7 +388,6 @@ export function useChat({ await handleRemoteMessage({ remoteUrl, messageContent: messageText, - setChatHistory: setChatHistory, }); return; } diff --git a/extensions/cli/src/ui/types.ts b/extensions/cli/src/ui/types.ts deleted file mode 100644 index a18e4a9b2..000000000 --- a/extensions/cli/src/ui/types.ts +++ /dev/null @@ -1,2 +0,0 @@ -// This file has been intentionally left empty after migration to ChatHistoryItem -// All types have been migrated to use @continuedev/core types