diff --git a/extensions/cli/src/commands/chat.ts b/extensions/cli/src/commands/chat.ts index 63bf8eb55..96e74c9ae 100644 --- a/extensions/cli/src/commands/chat.ts +++ b/extensions/cli/src/commands/chat.ts @@ -129,19 +129,18 @@ async function handleManualCompaction( const current = services.chatHistory.getHistory(); const result = await compactChatHistory(current, model, llmApi); - // Update service-driven history and persist session + // Update service-driven history (persistence handled by service) services.chatHistory.compact( result.compactedHistory, result.compactionIndex, ); - updateSessionHistory(result.compactedHistory); if (isHeadless) { safeStdout( JSON.stringify({ status: "success", message: "Chat history compacted", - historyLength: chatHistory.length, + historyLength: services.chatHistory.getHistory().length, }) + "\n", ); } else { @@ -188,7 +187,7 @@ async function handleAutoCompaction( message: "Auto-compacting triggered", contextUsage: calculateContextUsagePercentage( - countChatHistoryTokens(chatHistory), + countChatHistoryTokens(services.chatHistory.getHistory()), model, ) + "%", }) + "\n", @@ -198,11 +197,11 @@ async function handleAutoCompaction( if (!isHeadless) { console.info(chalk.green(message)); } else if (format === "json") { + // Omit history length here; service updates occur after compaction completes safeStdout( JSON.stringify({ status: "success", message: "Auto-compacted successfully", - historyLength: chatHistory.length, }) + "\n", ); } diff --git a/extensions/cli/src/commands/serve.helpers.ts b/extensions/cli/src/commands/serve.helpers.ts index be4fc1c7c..82ca902ea 100644 --- a/extensions/cli/src/commands/serve.helpers.ts +++ b/extensions/cli/src/commands/serve.helpers.ts @@ -3,6 +3,7 @@ import type { Session, ToolStatus } from "core/index.js"; import { services } from "../services/index.js"; import { streamChatResponse } from "../stream/streamChatResponse.js"; import { StreamCallbacks } from "../stream/streamChatResponse.types.js"; +import { logger } from "../util/logger.js"; // Modified version of streamChatResponse that supports interruption export async function streamChatResponseWithInterruption( @@ -65,14 +66,13 @@ export async function streamChatResponseWithInterruption( services.chatHistory.addSystemMessage( `WARNING: Tool ${toolName} requires permission`, ); - } catch { - state.session.history.push({ - message: { - role: "system", - content: `WARNING: Tool ${toolName} requires permission`, - }, - contextItems: [], - }); + } catch (err) { + // Do not mutate session history; ChatHistoryService is the source of truth + logger.error( + "Failed to add system message via ChatHistoryService", + err, + { context: "onToolPermissionRequest", toolName, requestId }, + ); } // Don't wait here - the streamChatResponse will handle waiting @@ -80,14 +80,13 @@ export async function streamChatResponseWithInterruption( onSystemMessage: (message: string) => { try { services.chatHistory.addSystemMessage(message); - } catch { - state.session.history.push({ - message: { - role: "system", - content: message, - }, - contextItems: [], - }); + } catch (err) { + // Do not mutate session history; ChatHistoryService is the source of truth + logger.error( + "Failed to add system message via ChatHistoryService", + err, + { context: "onSystemMessage" }, + ); } }, }; diff --git a/extensions/cli/src/commands/serve.ts b/extensions/cli/src/commands/serve.ts index c622dd4a4..b094553a0 100644 --- a/extensions/cli/src/commands/serve.ts +++ b/extensions/cli/src/commands/serve.ts @@ -158,7 +158,11 @@ export async function serve(prompt?: string, options: ServeOptions = {}) { // Ensure session history reflects ChatHistoryService state try { state.session.history = services.chatHistory.getHistory(); - } catch {} + } catch (e) { + logger.debug( + `Failed to sync session history from ChatHistoryService: ${formatError(e)}`, + ); + } res.json({ session: state.session, // Return session directly instead of converting isProcessing: state.isProcessing, diff --git a/extensions/cli/src/services/ChatHistoryService.ts b/extensions/cli/src/services/ChatHistoryService.ts index 93648568e..0ebc9de50 100644 --- a/extensions/cli/src/services/ChatHistoryService.ts +++ b/extensions/cli/src/services/ChatHistoryService.ts @@ -28,6 +28,12 @@ export class ChatHistoryService extends BaseService { // Simple undo/redo stacks for history snapshots private past: ChatHistoryItem[][] = []; private future: ChatHistoryItem[][] = []; + // Memoized snapshot for referential stability in getState() + private _memoSnapshot: { + stateRef: ChatHistoryState | null; + historyRef: ChatHistoryItem[] | null; + snapshot: ChatHistoryState | null; + } = { stateRef: null, historyRef: null, snapshot: null }; constructor() { super("ChatHistoryService", { @@ -41,9 +47,13 @@ export class ChatHistoryService extends BaseService { private setHistoryInternal( history: ChatHistoryItem[], - options: { recordUndo?: boolean } = {}, + options: { + recordUndo?: boolean; + compactionIndex?: number | null; + persist?: boolean; // set to false to skip persistence (rare) + } = {}, ): void { - const { recordUndo = true } = options; + const { recordUndo = true, compactionIndex, persist } = options; const prev = this.currentState.history; if (recordUndo) { this.past.push([...prev]); @@ -51,12 +61,15 @@ export class ChatHistoryService extends BaseService { } this.setState({ history: [...history], - compactionIndex: this.findCompactionIndex(history), + compactionIndex: + compactionIndex === undefined + ? this.findCompactionIndex(history) + : compactionIndex, }); if (this.currentState.isRemoteMode) { // Skip persistence in remote mode - } else { + } else if (persist !== false) { updateSessionHistory(history); } } @@ -189,15 +202,7 @@ export class ChatHistoryService extends BaseService { }); const newHistory = [...this.currentState.history, newMessage]; - this.setState({ - history: newHistory, - }); - - if (this.currentState.isRemoteMode) { - // Skip persistence in remote mode - } else { - updateSessionHistory(newHistory); - } + this.setHistoryInternal(newHistory); logger.debug("Added system message", { contentLength: content.length, @@ -346,14 +351,7 @@ export class ChatHistoryService extends BaseService { * Perform compaction on the history */ compact(newHistory: ChatHistoryItem[], compactionIndex: number): void { - this.past.push([...this.currentState.history]); - this.future = []; - this.setState({ history: newHistory, compactionIndex }); - if (this.currentState.isRemoteMode) { - // Skip persistence in remote mode - } else { - updateSessionHistory(newHistory); - } + this.setHistoryInternal(newHistory, { compactionIndex }); logger.debug("Compacted history", { oldLength: this.currentState.history.length, @@ -366,14 +364,7 @@ export class ChatHistoryService extends BaseService { * Clear the chat history */ clear(): void { - this.past.push([...this.currentState.history]); - this.future = []; - this.setState({ history: [], compactionIndex: null }); - if (this.currentState.isRemoteMode) { - // Skip persistence in remote mode - } else { - updateSessionHistory([]); - } + this.setHistoryInternal([], { compactionIndex: null }); logger.debug("Cleared chat history"); } @@ -384,11 +375,9 @@ export class ChatHistoryService extends BaseService { async loadSession(sessionId: string): Promise { const session = loadSessionById(sessionId); if (session) { - this.setState({ - history: session.history, - sessionId: session.sessionId, - compactionIndex: this.findCompactionIndex(session.history), - }); + // Load new history without recording undo; set sessionId separately + this.setHistoryInternal(session.history, { recordUndo: false }); + this.setState({ sessionId: session.sessionId }); logger.debug("Loaded session", { sessionId, @@ -503,9 +492,43 @@ export class ChatHistoryService extends BaseService { * Override getState to ensure deep immutability for history array */ getState(): ChatHistoryState { - return { - ...this.currentState, - history: [...this.currentState.history], - }; + const stateRef = this.currentState; + const historyRef = stateRef.history; + + // If neither the state object nor the history reference changed, + // return the same memoized snapshot to preserve referential stability + if ( + this._memoSnapshot.snapshot && + this._memoSnapshot.stateRef === stateRef && + this._memoSnapshot.historyRef === historyRef + ) { + return this._memoSnapshot.snapshot; + } + + // Build a memoized snapshot object with getters to: + // - keep the outer object reference stable when unchanged + // - return a fresh copy of history on each access to prevent external mutation + const snapshot = {} as ChatHistoryState; + Object.defineProperties(snapshot, { + history: { + enumerable: true, + get: () => [...stateRef.history], + }, + compactionIndex: { + enumerable: true, + get: () => stateRef.compactionIndex, + }, + sessionId: { + enumerable: true, + get: () => stateRef.sessionId, + }, + isRemoteMode: { + enumerable: true, + get: () => stateRef.isRemoteMode, + }, + }); + + this._memoSnapshot = { stateRef, historyRef, snapshot }; + return snapshot; } } diff --git a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts index fa9551aa6..d169f2faf 100644 --- a/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.remote.helpers.ts @@ -97,8 +97,29 @@ function updateStateFromRemote({ if (state.session && state.session.history) { 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); + if (!services.chatHistory.isRemoteMode()) { + services.chatHistory.setRemoteMode(true); + } + // Avoid redundant updates: only set when history actually changed + try { + const current = services.chatHistory.getHistory(); + let changed = current.length !== newHistory.length; + if (!changed) { + for (let i = 0; i < current.length; i++) { + // Deep compare items; break on first difference + if (JSON.stringify(current[i]) !== JSON.stringify(newHistory[i])) { + changed = true; + break; + } + } + } + if (changed) { + services.chatHistory.setHistory(newHistory); + } + } catch { + // As a fallback, attempt to set history (service may handle no-op) + services.chatHistory.setHistory(newHistory); + } } // Update processing state diff --git a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts index ff8614892..213c0212f 100644 --- a/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts +++ b/extensions/cli/src/ui/hooks/useChat.stream.helpers.ts @@ -1,5 +1,7 @@ import type { ChatHistoryItem, ToolCallState, ToolStatus } from "core/index.js"; +import { logger } from "src/util/logger.js"; + import { services } from "../../services/index.js"; import { getCurrentSession, updateSessionTitle } from "../../session.js"; @@ -42,7 +44,9 @@ export function createStreamCallbacks( }, ]); } - } catch {} + } catch (error) { + logger.error("Failed to update chat history", { error }); + } // Generate session title after first assistant response if (content && llmApi && model) { const currentSession = getCurrentSession();