From e751a1b71deff30a928b0b77aa2e2844feff22e8 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 1 Sep 2025 12:15:00 -0700 Subject: [PATCH] refactor: phase 3 --- extensions/cli/src/stream/handleToolCalls.ts | 81 +++++++++++++++---- .../cli/src/stream/streamChatResponse.ts | 21 ++++- .../src/ui/hooks/useChat.stream.helpers.ts | 28 +++++-- extensions/cli/src/ui/hooks/useChat.ts | 14 ++-- 4 files changed, 116 insertions(+), 28 deletions(-) diff --git a/extensions/cli/src/stream/handleToolCalls.ts b/extensions/cli/src/stream/handleToolCalls.ts index aa37a25d7..79db12e9e 100644 --- a/extensions/cli/src/stream/handleToolCalls.ts +++ b/extensions/cli/src/stream/handleToolCalls.ts @@ -9,6 +9,7 @@ import { MCPServiceState, MCPTool, SERVICE_NAMES, + services, } from "../services/index.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { getAllBuiltinTools, ToolCall } from "../tools/index.js"; @@ -27,14 +28,46 @@ export async function handleToolCalls( callbacks: StreamCallbacks | undefined, isHeadless: boolean, ): Promise { + const chatHistorySvc = services.chatHistory; + const useService = typeof chatHistorySvc?.isReady === "function" && chatHistorySvc.isReady(); if (toolCalls.length === 0) { if (content) { - chatHistory.push( - createHistoryItem({ - role: "assistant", - content, - }), - ); + // De-duplication: if the last message already matches, skip adding + const last = chatHistory[chatHistory.length - 1]; + const isDuplicateLocal = + !!last && + last.message.role === "assistant" && + typeof last.message.content === "string" && + last.message.content === content && + !(last as any).toolCallStates?.length; + + if (!isDuplicateLocal) { + // Keep the local array updated for compatibility + chatHistory.push( + createHistoryItem({ + role: "assistant", + content, + }), + ); + } + + if (useService) { + 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); + } + } } return false; } @@ -68,7 +101,11 @@ export async function handleToolCalls( })), }; + // Always keep the local array updated for compatibility chatHistory.push(createHistoryItem(assistantMessage, [], toolCallStates)); + if (useService) { + chatHistorySvc.addAssistantMessage(assistantMessage.content || "", toolCalls); + } // First preprocess the tool calls const { preprocessedCalls, errorChatEntries } = @@ -77,13 +114,16 @@ export async function handleToolCalls( // 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, - }), - ); + const item = createHistoryItem({ + role: "tool", + content: stripImages(errorEntry.content) || "", + toolCallId: errorEntry.tool_call_id, + }); + // Keep local array updated + chatHistory.push(item); + if (useService) { + chatHistorySvc.addHistoryItem(item); + } }); // Execute the valid preprocessed tool calls @@ -100,7 +140,9 @@ export async function handleToolCalls( // 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 resultContent = + typeof toolResult.content === "string" ? toolResult.content : ""; + // Update local array state const lastAssistantIndex = chatHistory.findLastIndex( (item) => item.message.role === "assistant" && item.toolCallStates, ); @@ -117,14 +159,21 @@ export async function handleToolCalls( toolState.status = hasRejection ? "canceled" : "done"; toolState.output = [ { - content: - typeof toolResult.content === "string" ? toolResult.content : "", + content: resultContent, name: `Tool Result`, description: "Tool execution result", }, ]; } } + + if (useService) { + chatHistorySvc.addToolResult( + toolResult.tool_call_id, + resultContent, + hasRejection ? ("canceled" as ToolStatus) : ("done" as ToolStatus), + ); + } }); return false; } diff --git a/extensions/cli/src/stream/streamChatResponse.ts b/extensions/cli/src/stream/streamChatResponse.ts index 300ea5b24..1defd3c2e 100644 --- a/extensions/cli/src/stream/streamChatResponse.ts +++ b/extensions/cli/src/stream/streamChatResponse.ts @@ -8,7 +8,7 @@ import type { ChatCompletionTool, } from "openai/resources.mjs"; -import { getServiceSync, SERVICE_NAMES } from "../services/index.js"; +import { getServiceSync, SERVICE_NAMES, services } from "../services/index.js"; import { systemMessageService } from "../services/SystemMessageService.js"; import type { ToolPermissionServiceState } from "../services/ToolPermissionService.js"; import { telemetryService } from "../telemetry/telemetryService.js"; @@ -320,6 +320,13 @@ export async function streamChatResponse( let finalResponse = ""; while (true) { + // If ChatHistoryService is available, refresh local chatHistory view + const chatHistorySvc = services.chatHistory; + if (typeof chatHistorySvc?.isReady === "function" && chatHistorySvc.isReady()) { + try { + chatHistory = chatHistorySvc.getHistory(); + } catch {} + } logger.debug("Starting conversation iteration"); // Recompute tools on each iteration to handle mode changes during streaming @@ -385,7 +392,17 @@ export async function streamChatResponse( // Only update chat history if compaction actually occurred if (wasCompacted) { - chatHistory = [...updatedChatHistory]; + // If service is available, set history there; otherwise update local copy + const chatHistorySvc2 = services.chatHistory; + if ( + typeof chatHistorySvc2?.isReady === "function" && + chatHistorySvc2.isReady() + ) { + chatHistorySvc2.setHistory(updatedChatHistory); + chatHistory = chatHistorySvc2.getHistory(); + } else { + chatHistory = [...updatedChatHistory]; + } } } diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index aa2c19579..aeac13239 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -1,6 +1,7 @@ import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; import { getCurrentSession, updateSessionTitle } from "../../session.js"; +import { services } from "../../services/index.js"; import { generateSessionTitle } from "./useChat.helpers.js"; @@ -23,6 +24,7 @@ export function createStreamCallbacks( onContent: (_: string) => {}, onContentComplete: async (content: string) => { + // Update local React state for UI setChatHistory((prev) => [ ...prev, { @@ -35,6 +37,14 @@ export function createStreamCallbacks( }, ]); + // Also update service; handleToolCalls will de-dup when no tools + try { + const svc = services.chatHistory; + if (typeof svc?.isReady === "function" && svc.isReady()) { + svc.addAssistantMessage(content); + } + } catch {} + // Generate session title after first assistant response if (content && llmApi && model) { const currentSession = getCurrentSession(); @@ -52,10 +62,10 @@ export function createStreamCallbacks( }, onToolStart: (toolName: string, toolArgs?: any) => { + // Preserve local UI behavior: create a new assistant message representing the tool call setChatHistory((prev) => { const newHistory = [...prev]; - // Always create a new assistant message for each tool call const toolCallId = `tool_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`; const toolCallState: ToolCallState = { toolCallId: toolCallId, @@ -92,20 +102,21 @@ export function createStreamCallbacks( return newHistory; }); + // Do not update service here; handleToolCalls will add tool call message }, onToolResult: (result: string, toolName: string, status: ToolStatus) => { + // Update local UI-only state; service is updated through handleToolCalls setChatHistory((prev) => { const newHistory = [...prev]; - // Find the tool call state and update it for (let i = newHistory.length - 1; i >= 0; i--) { const item = newHistory[i]; if (item.toolCallStates) { const toolState = item.toolCallStates.find( (ts) => ts.toolCall.function.name === toolName && - ts.status === "calling", + (ts.status === "calling" || ts.status === "generated"), ); if (toolState) { @@ -130,7 +141,6 @@ export function createStreamCallbacks( setChatHistory((prev) => { const newHistory = [...prev]; - // Find the tool call state and mark it as errored if (toolName) { for (let i = newHistory.length - 1; i >= 0; i--) { const item = newHistory[i]; @@ -138,7 +148,7 @@ export function createStreamCallbacks( const toolState = item.toolCallStates.find( (ts) => ts.toolCall.function.name === toolName && - ts.status === "calling", + (ts.status === "calling" || ts.status === "generated"), ); if (toolState) { @@ -184,6 +194,14 @@ export function createStreamCallbacks( }, onSystemMessage: (message: string) => { + try { + const svc = services.chatHistory; + if (typeof svc?.isReady === "function" && svc.isReady()) { + svc.addSystemMessage(message); + return; + } + } catch {} + // Fallback to local state if service unavailable setChatHistory((prev) => [ ...prev, { diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index ef7ea48f3..0bdad1d4f 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -83,10 +83,13 @@ export function useChat({ const [chatHistory, setChatHistoryOriginal] = useState( () => currentSession.history, ); - - // Create wrapped setChatHistory that syncs with service - // Use a regular variable instead of ref to avoid type issues - let setChatHistory = setChatHistoryOriginal; + // Wrapped setter ref for Phase 2 wrapper + const setChatHistoryRef = useRef( + setChatHistoryOriginal, + ); + // Proxy setter that always calls the latest wrapped function + const setChatHistory: typeof setChatHistoryOriginal = (value) => + setChatHistoryRef.current(value); // Initialize wrapper on first render useEffect(() => { @@ -100,7 +103,8 @@ export function useChat({ }); // Create wrapped setState and setup sync - setChatHistory = wrapperRef.current.createWrappedSetState(setChatHistoryOriginal); + setChatHistoryRef.current = + wrapperRef.current.createWrappedSetState(setChatHistoryOriginal); wrapperRef.current.setupSync(setChatHistoryOriginal); // Initialize service with existing state if any