From 1db74ef30084201fecdee5e985fa7a35f285bf0e Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 1 Sep 2025 12:28:26 -0700 Subject: [PATCH] refactor: phase 4 --- .../src/services/ChatHistoryService.test.ts | 12 +- .../cli/src/services/ChatHistoryService.ts | 33 +- .../ChatHistoryServiceWrapper.test.ts | 181 ---------- .../src/services/ChatHistoryServiceWrapper.ts | 117 ------- .../__tests__/TUIChat.slashCommands.test.tsx | 6 +- extensions/cli/src/ui/hooks/useChat.ts | 68 ++-- .../cli/src/ui/hooks/useChat.wrapper.test.tsx | 315 ------------------ 7 files changed, 50 insertions(+), 682 deletions(-) delete mode 100644 extensions/cli/src/services/ChatHistoryServiceWrapper.test.ts delete mode 100644 extensions/cli/src/services/ChatHistoryServiceWrapper.ts delete mode 100644 extensions/cli/src/ui/hooks/useChat.wrapper.test.tsx diff --git a/extensions/cli/src/services/ChatHistoryService.test.ts b/extensions/cli/src/services/ChatHistoryService.test.ts index 43567fb39..2051c3cf9 100644 --- a/extensions/cli/src/services/ChatHistoryService.test.ts +++ b/extensions/cli/src/services/ChatHistoryService.test.ts @@ -68,10 +68,7 @@ describe("ChatHistoryService", () => { message: { role: "user", content: "First message" }, contextItems: [], }, - { - message: { role: "system", content: "[Compacted] Summary of conversation" }, - contextItems: [], - }, + { message: { role: "assistant", content: "Summary here" }, contextItems: [], conversationSummary: "Summary here" }, { message: { role: "user", content: "After compaction" }, contextItems: [], @@ -390,10 +387,7 @@ describe("ChatHistoryService", () => { it("should detect compaction index when setting history", () => { const historyWithCompaction: ChatHistoryItem[] = [ - { - message: { role: "system", content: "[Compacted] Old stuff" }, - contextItems: [], - }, + { message: { role: "assistant", content: "old summary" }, contextItems: [], conversationSummary: "old summary" }, { message: { role: "user", content: "Recent message" }, contextItems: [], @@ -484,4 +478,4 @@ describe("ChatHistoryService", () => { ); }); }); -}); \ No newline at end of file +}); diff --git a/extensions/cli/src/services/ChatHistoryService.ts b/extensions/cli/src/services/ChatHistoryService.ts index ed0813e9a..046a6dd25 100644 --- a/extensions/cli/src/services/ChatHistoryService.ts +++ b/extensions/cli/src/services/ChatHistoryService.ts @@ -28,6 +28,7 @@ export class ChatHistoryService extends BaseService { sessionId: "", isRemoteMode: false, }); + this.setMaxListeners(50); } /** @@ -336,13 +337,15 @@ export class ChatHistoryService extends BaseService { */ getHistoryForLLM(compactionIndex?: number | null): ChatHistoryItem[] { const index = compactionIndex ?? this.currentState.compactionIndex; - - if (index !== null && index !== undefined && index < this.currentState.history.length) { - // Return only messages after compaction, plus the compacted summary - return this.currentState.history.slice(index); + const full = this.currentState.history; + if (index === null || index === undefined || index >= full.length) { + return this.getHistory(); } - - return this.getHistory(); + const systemMessage = full[0]?.message?.role === "system" ? full[0] : null; + const messagesFromCompaction = full.slice(index); + return systemMessage && index > 0 + ? [systemMessage, ...messagesFromCompaction] + : messagesFromCompaction; } /** @@ -378,17 +381,8 @@ export class ChatHistoryService extends BaseService { * Find compaction index in history */ private findCompactionIndex(history: ChatHistoryItem[]): number | null { - for (let i = history.length - 1; i >= 0; i--) { - const message = history[i].message; - if (message.role === "system") { - // Handle both string and MessagePart array content - const content = message.content; - if (typeof content === "string" && content.includes("[Compacted]")) { - return i; - } - } - } - return null; + const idx = history.findIndex((item) => item.conversationSummary !== undefined); + return idx === -1 ? null : idx; } /** @@ -398,6 +392,8 @@ export class ChatHistoryService extends BaseService { return this.currentState.sessionId; } + + /** * Check if in remote mode */ @@ -424,6 +420,3 @@ export class ChatHistoryService extends BaseService { }; } } - -// Export singleton instance for migration compatibility -export const chatHistoryService = new ChatHistoryService(); \ No newline at end of file diff --git a/extensions/cli/src/services/ChatHistoryServiceWrapper.test.ts b/extensions/cli/src/services/ChatHistoryServiceWrapper.test.ts deleted file mode 100644 index 67dadabb0..000000000 --- a/extensions/cli/src/services/ChatHistoryServiceWrapper.test.ts +++ /dev/null @@ -1,181 +0,0 @@ -import type { ChatHistoryItem } from "core/index.js"; -import { describe, it, expect, vi, beforeEach } from "vitest"; - -import { ChatHistoryService } from "./ChatHistoryService.js"; -import { ChatHistoryServiceWrapper } from "./ChatHistoryServiceWrapper.js"; - -describe("ChatHistoryServiceWrapper", () => { - let service: ChatHistoryService; - let wrapper: ChatHistoryServiceWrapper; - - beforeEach(() => { - service = new ChatHistoryService(); - wrapper = new ChatHistoryServiceWrapper(service); - }); - - describe("createWrappedSetState", () => { - it("should sync direct value updates to service", () => { - const originalSetState = vi.fn(); - const wrappedSetState = wrapper.createWrappedSetState(originalSetState); - - const newHistory: ChatHistoryItem[] = [ - { - message: { role: "user", content: "test" }, - contextItems: [], - }, - ]; - - wrappedSetState(newHistory); - - expect(service.getHistory()).toEqual(newHistory); - expect(originalSetState).toHaveBeenCalledWith(newHistory); - }); - - it("should sync function updates to service", () => { - const originalSetState = vi.fn(); - const wrappedSetState = wrapper.createWrappedSetState(originalSetState); - - const initialHistory: ChatHistoryItem[] = [ - { - message: { role: "system", content: "initial" }, - contextItems: [], - }, - ]; - service.setHistory(initialHistory); - - const newMessage: ChatHistoryItem = { - message: { role: "user", content: "test" }, - contextItems: [], - }; - - wrappedSetState((prev) => [...prev, newMessage]); - - const expectedHistory = [...initialHistory, newMessage]; - expect(service.getHistory()).toEqual(expectedHistory); - expect(originalSetState).toHaveBeenCalledWith(expectedHistory); - }); - - it("should handle errors when syncing to service", () => { - const originalSetState = vi.fn(); - const wrappedSetState = wrapper.createWrappedSetState(originalSetState); - - // Mock service.setHistory to throw an error - vi.spyOn(service, "setHistory").mockImplementation(() => { - throw new Error("Service error"); - }); - - const newHistory: ChatHistoryItem[] = [ - { - message: { role: "user", content: "test" }, - contextItems: [], - }, - ]; - - // Should not throw, just log error - expect(() => wrappedSetState(newHistory)).not.toThrow(); - - // React state should still be updated - expect(originalSetState).toHaveBeenCalledWith(newHistory); - }); - }); - - describe("setupSync", () => { - it("should sync service changes to React state", () => { - const setChatHistory = vi.fn(); - wrapper.setupSync(setChatHistory); - - const newHistory: ChatHistoryItem[] = [ - { - message: { role: "user", content: "test" }, - contextItems: [], - }, - ]; - - service.setHistory(newHistory); - - expect(setChatHistory).toHaveBeenCalledWith(newHistory); - }); - - it("should prevent infinite loops when syncing", () => { - const originalSetState = vi.fn(); - const wrappedSetState = wrapper.createWrappedSetState(originalSetState); - - wrapper.setupSync(wrappedSetState); - - const newHistory: ChatHistoryItem[] = [ - { - message: { role: "user", content: "test" }, - contextItems: [], - }, - ]; - - // This should trigger sync to React state, which uses wrapped setState - // The wrapper should detect it's a service update and not sync back - service.setHistory(newHistory); - - // Service setHistory should only be called once (the initial call above) - const setHistorySpy = vi.spyOn(service, "setHistory"); - expect(setHistorySpy).not.toHaveBeenCalled(); - }); - }); - - describe("initializeFromState", () => { - it("should initialize service with existing history", () => { - const existingHistory: ChatHistoryItem[] = [ - { - message: { role: "system", content: "system message" }, - contextItems: [], - }, - { - message: { role: "user", content: "hello" }, - contextItems: [], - }, - ]; - - wrapper.initializeFromState(existingHistory); - - expect(service.getHistory()).toEqual(existingHistory); - }); - - it("should not initialize if history is empty", () => { - const setHistorySpy = vi.spyOn(service, "setHistory"); - - wrapper.initializeFromState([]); - - expect(setHistorySpy).not.toHaveBeenCalled(); - }); - }); - - describe("cleanup", () => { - it("should unsubscribe from service on cleanup", () => { - const setChatHistory = vi.fn(); - wrapper.setupSync(setChatHistory); - - wrapper.cleanup(); - - // After cleanup, service changes should not trigger React state updates - const newHistory: ChatHistoryItem[] = [ - { - message: { role: "user", content: "test" }, - contextItems: [], - }, - ]; - - service.setHistory(newHistory); - - // Should only be called once (from the initial setupSync) - expect(setChatHistory).not.toHaveBeenCalled(); - }); - - it("should handle cleanup when no subscription exists", () => { - // Should not throw - expect(() => wrapper.cleanup()).not.toThrow(); - }); - }); - - describe("getService", () => { - it("should return the underlying service", () => { - expect(wrapper.getService()).toBe(service); - }); - }); -}); \ No newline at end of file diff --git a/extensions/cli/src/services/ChatHistoryServiceWrapper.ts b/extensions/cli/src/services/ChatHistoryServiceWrapper.ts deleted file mode 100644 index b351ca0db..000000000 --- a/extensions/cli/src/services/ChatHistoryServiceWrapper.ts +++ /dev/null @@ -1,117 +0,0 @@ -/** - * ChatHistoryServiceWrapper - Phase 2 Compatibility Layer - * - * This wrapper provides a bridge between the old React state-based chat history - * and the new ChatHistoryService. It allows for gradual migration by: - * 1. Intercepting setState calls and syncing to the service - * 2. Subscribing to service changes and updating React state - * 3. Providing a migration path without breaking existing code - */ - -import type { ChatHistoryItem } from "core/index.js"; -import { Dispatch, SetStateAction } from "react"; - -import { logger } from "../util/logger.js"; - -import { ChatHistoryService } from "./ChatHistoryService.js"; - -export type SetChatHistoryFunction = Dispatch>; - -export class ChatHistoryServiceWrapper { - private service: ChatHistoryService; - private originalSetState: SetChatHistoryFunction | null = null; - private isServiceUpdate = false; // Flag to prevent infinite loops - private unsubscribe: (() => void) | null = null; - - constructor(service: ChatHistoryService) { - this.service = service; - } - - /** - * Creates a wrapped setState function that syncs with the service - */ - createWrappedSetState(originalSetState: SetChatHistoryFunction): SetChatHistoryFunction { - this.originalSetState = originalSetState; - - return (value: SetStateAction) => { - // If this update is coming from the service, just pass through - if (this.isServiceUpdate) { - originalSetState(value); - return; - } - - // Handle both function and direct value updates - const newHistory = typeof value === 'function' - ? value(this.service.getHistory()) - : value; - - // Sync to service - try { - this.service.setHistory(newHistory); - logger.debug('Synced React state to ChatHistoryService', { - historyLength: newHistory.length - }); - } catch (error) { - logger.error('Failed to sync to ChatHistoryService', { error }); - } - - // Update React state - originalSetState(newHistory); - }; - } - - /** - * Sets up bidirectional sync between React state and service - */ - setupSync(setChatHistory: SetChatHistoryFunction): void { - // Subscribe to service changes and update React state - const listener = () => { - this.isServiceUpdate = true; - try { - const history = this.service.getHistory(); - setChatHistory(history); - logger.debug('Synced ChatHistoryService to React state', { - historyLength: history.length - }); - } finally { - this.isServiceUpdate = false; - } - }; - - this.service.on('stateChanged', listener); - - // Store unsubscribe function - this.unsubscribe = () => { - this.service.off('stateChanged', listener); - }; - } - - /** - * Initializes the service with existing history - */ - initializeFromState(history: ChatHistoryItem[]): void { - if (history.length > 0) { - this.service.setHistory(history); - logger.debug('Initialized ChatHistoryService from React state', { - historyLength: history.length - }); - } - } - - /** - * Cleans up subscriptions - */ - cleanup(): void { - if (this.unsubscribe) { - this.unsubscribe(); - this.unsubscribe = null; - } - } - - /** - * Get the underlying service for direct access when needed - */ - getService(): ChatHistoryService { - return this.service; - } -} \ No newline at end of file diff --git a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx index b7c2d6b27..3980903cc 100644 --- a/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx +++ b/extensions/cli/src/ui/__tests__/TUIChat.slashCommands.test.tsx @@ -30,8 +30,8 @@ describe("TUIChat - Slash Commands Tests", () => { // Type /log to trigger slash command filtering stdin.write("/log"); - // Wait a bit for the UI to update - await new Promise((resolve) => setTimeout(resolve, 50)); + // Wait a bit for the UI to update (remote mode can be slower) + await new Promise((resolve) => setTimeout(resolve, mode === "remote" ? 200 : 50)); const frame = lastFrame(); @@ -81,7 +81,7 @@ describe("TUIChat - Slash Commands Tests", () => { // Type just / stdin.write("/"); - await new Promise((resolve) => setTimeout(resolve, 50)); + await new Promise((resolve) => setTimeout(resolve, mode === "remote" ? 120 : 50)); const frame = lastFrame(); diff --git a/extensions/cli/src/ui/hooks/useChat.ts b/extensions/cli/src/ui/hooks/useChat.ts index 0bdad1d4f..3fa345f4b 100644 --- a/extensions/cli/src/ui/hooks/useChat.ts +++ b/extensions/cli/src/ui/hooks/useChat.ts @@ -4,7 +4,6 @@ import { useEffect, useState, useRef } from "react"; import { findCompactionIndex } from "../../compaction.js"; import { toolPermissionManager } from "../../permissions/permissionManager.js"; -import { ChatHistoryServiceWrapper } from "../../services/ChatHistoryServiceWrapper.js"; import { services } from "../../services/index.js"; import { createSession, @@ -58,8 +57,8 @@ export function useChat({ }: UseChatProps) { const { exit } = useApp(); - // Initialize ChatHistoryServiceWrapper for Phase 2 migration - const wrapperRef = useRef(null); + // Track service subscription + const serviceListenerCleanupRef = useRef void)>(null); // Store the current session const [currentSession, setCurrentSession] = useState(() => { @@ -80,47 +79,42 @@ export function useChat({ return createSession([]); }); - const [chatHistory, setChatHistoryOriginal] = useState( - () => currentSession.history, + // Local view of history driven solely by ChatHistoryService + const [chatHistory, setChatHistoryView] = useState(() => + services.chatHistory?.isReady() ? services.chatHistory.getHistory() : currentSession.history, ); - // 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); + // Proxy setter: apply changes to ChatHistoryService (single source of truth) + const setChatHistory: React.Dispatch< + React.SetStateAction + > = (value) => { + const svc = services.chatHistory; + const current = svc.getHistory(); + const next = typeof value === "function" ? (value as any)(current) : value; + svc.setHistory(next); + }; - // Initialize wrapper on first render + // Initialize ChatHistoryService and subscribe to updates useEffect(() => { - if (!wrapperRef.current) { - const chatHistoryService = services.chatHistory; - wrapperRef.current = new ChatHistoryServiceWrapper(chatHistoryService); - - // Initialize service with session data - chatHistoryService.initialize(currentSession, isRemoteMode).catch((error) => { - logger.error('Failed to initialize ChatHistoryService', { error }); + const svc = services.chatHistory; + svc + .initialize(currentSession, isRemoteMode) + .then(() => { + setChatHistoryView(svc.getHistory()); + const listener = () => { + setChatHistoryView(svc.getHistory()); + }; + svc.on("stateChanged", listener); + serviceListenerCleanupRef.current = () => svc.off("stateChanged", listener); + }) + .catch((error) => { + logger.error("Failed to initialize ChatHistoryService", { error }); }); - - // Create wrapped setState and setup sync - setChatHistoryRef.current = - wrapperRef.current.createWrappedSetState(setChatHistoryOriginal); - wrapperRef.current.setupSync(setChatHistoryOriginal); - - // Initialize service with existing state if any - if (chatHistory.length > 0) { - wrapperRef.current.initializeFromState(chatHistory); - } - } return () => { - // Cleanup on unmount - if (wrapperRef.current) { - wrapperRef.current.cleanup(); - wrapperRef.current = null; - } + serviceListenerCleanupRef.current?.(); + serviceListenerCleanupRef.current = null; }; - }, []); // Run only once on mount + }, []); const [isWaitingForResponse, setIsWaitingForResponse] = useState(false); const [responseStartTime, setResponseStartTime] = useState( diff --git a/extensions/cli/src/ui/hooks/useChat.wrapper.test.tsx b/extensions/cli/src/ui/hooks/useChat.wrapper.test.tsx deleted file mode 100644 index 3068a3784..000000000 --- a/extensions/cli/src/ui/hooks/useChat.wrapper.test.tsx +++ /dev/null @@ -1,315 +0,0 @@ -/** - * @vitest-environment jsdom - */ -import { renderHook, act } from "@testing-library/react"; -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - -import { ChatHistoryService } from "../../services/ChatHistoryService.js"; -import { services, initializeServices } from "../../services/index.js"; -import { mockLlmApi } from "../../test-helpers/ui-test-context.js"; - -import { useChat } from "./useChat.js"; - -// Mock dependencies -vi.mock("ink", () => ({ - useApp: () => ({ exit: vi.fn() }), -})); - -vi.mock("../../util/logger.js", () => ({ - logger: { - debug: vi.fn(), - error: vi.fn(), - warn: vi.fn(), - }, -})); - -vi.mock("../../session.js", () => ({ - createSession: (history: any[] = []) => ({ - sessionId: "test-session", - history, - }), - loadSession: vi.fn(() => null), - updateSessionHistory: vi.fn(), - loadSessionById: vi.fn(), -})); - -vi.mock("../../slashCommands.js", () => ({ - handleSlashCommands: vi.fn(() => null), -})); - -vi.mock("../../telemetry/telemetryService.js", () => ({ - telemetryService: { - startActiveTime: vi.fn(), - stopActiveTime: vi.fn(), - addEventProperties: vi.fn(), - trackUserMessage: vi.fn(), - }, -})); - -vi.mock("../../permissions/permissionManager.js", () => ({ - toolPermissionManager: { - approveRequest: vi.fn(), - rejectRequest: vi.fn(), - }, -})); - -vi.mock("./useChat.helpers.js", () => ({ - formatMessageWithFiles: vi.fn((message: string, files: any[]) => ({ - messageText: message, - contextItems: [], - })), - handleAutoCompaction: vi.fn(async ({ chatHistory }: any) => ({ - currentChatHistory: chatHistory, - currentCompactionIndex: null, - })), - handleCompactCommand: vi.fn(async () => {}), - handleSpecialCommands: vi.fn(async () => false), - initChatHistory: vi.fn(async () => [ - { - message: { role: "system", content: "Test system message" }, - contextItems: [], - }, - ]), - processSlashCommandResult: vi.fn(() => null), - trackUserMessage: vi.fn(), -})); - -vi.mock("./useChat.remote.helpers.js", () => ({ - handleRemoteMessage: vi.fn(async () => {}), - setupRemotePolling: vi.fn(() => () => {}), -})); - -vi.mock("./useChat.stream.helpers.js", () => ({ - createStreamCallbacks: vi.fn(() => ({ - onContent: vi.fn(), - onFinalMessage: vi.fn(), - })), - executeStreaming: vi.fn(async () => {}), -})); - -describe("useChat with ChatHistoryServiceWrapper", () => { - let chatHistoryService: ChatHistoryService; - - beforeEach(async () => { - // Initialize services - await initializeServices({ - skipOnboarding: true, - headless: true, - }); - - // Get the service instance - chatHistoryService = services.chatHistory; - - // Ensure service is initialized - if (!chatHistoryService.isReady()) { - await chatHistoryService.initialize(); - } - }); - - afterEach(() => { - vi.clearAllMocks(); - }); - - it("should initialize ChatHistoryService and sync with React state", async () => { - const { result } = renderHook(() => - useChat({ - model: undefined, - llmApi: mockLlmApi, - assistant: undefined, - onShowConfigSelector: vi.fn(), - onShowMCPSelector: vi.fn(), - }), - ); - - // Wait for initialization - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Verify service is initialized - expect(chatHistoryService.isReady()).toBe(true); - - // Verify initial history includes system message - expect(result.current.chatHistory).toHaveLength(1); - expect(result.current.chatHistory[0].message.role).toBe("system"); - }); - - it("should sync React state updates to ChatHistoryService", async () => { - const { result } = renderHook(() => - useChat({ - model: undefined, - llmApi: mockLlmApi, - assistant: undefined, - onShowConfigSelector: vi.fn(), - onShowMCPSelector: vi.fn(), - }), - ); - - // Wait for initialization - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Update chat history through React setter - const newMessage = { - message: { role: "user" as const, content: "Hello" }, - contextItems: [], - }; - - act(() => { - result.current.setChatHistory((prev) => [...prev, newMessage]); - }); - - // Verify service was updated - const serviceHistory = chatHistoryService.getHistory(); - expect(serviceHistory).toHaveLength(2); - expect(serviceHistory[1]).toEqual(newMessage); - - // Verify React state was updated - expect(result.current.chatHistory).toHaveLength(2); - expect(result.current.chatHistory[1]).toEqual(newMessage); - }); - - it("should sync ChatHistoryService updates to React state", async () => { - const { result } = renderHook(() => - useChat({ - model: undefined, - llmApi: mockLlmApi, - assistant: undefined, - onShowConfigSelector: vi.fn(), - onShowMCPSelector: vi.fn(), - }), - ); - - // Wait for initialization - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Update service directly - act(() => { - chatHistoryService.addUserMessage("Hello from service"); - }); - - // Wait for state propagation - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - - // Verify React state was updated - expect(result.current.chatHistory).toHaveLength(2); - expect(result.current.chatHistory[1].message.content).toBe("Hello from service"); - }); - - it("should prevent infinite loops during bidirectional sync", async () => { - const { result } = renderHook(() => - useChat({ - model: undefined, - llmApi: mockLlmApi, - assistant: undefined, - onShowConfigSelector: vi.fn(), - onShowMCPSelector: vi.fn(), - }), - ); - - // Wait for initialization - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Spy on setHistory to count calls - const setHistorySpy = vi.spyOn(chatHistoryService, "setHistory"); - - // Update through React state - act(() => { - result.current.setChatHistory((prev) => [ - ...prev, - { - message: { role: "user" as const, content: "Test" }, - contextItems: [], - }, - ]); - }); - - // Wait for any potential propagation - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Should be called only once (from React to service) - expect(setHistorySpy).toHaveBeenCalledTimes(1); - - // Now update through service - setHistorySpy.mockClear(); - act(() => { - chatHistoryService.addUserMessage("Service update"); - }); - - // Wait for propagation - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // setHistory should not be called (update originated from service) - expect(setHistorySpy).not.toHaveBeenCalled(); - }); - - it("should handle function updates to setState", async () => { - const { result } = renderHook(() => - useChat({ - model: undefined, - llmApi: mockLlmApi, - assistant: undefined, - onShowConfigSelector: vi.fn(), - onShowMCPSelector: vi.fn(), - }), - ); - - // Wait for initialization - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Use function form of setState - act(() => { - result.current.setChatHistory((prev) => { - const filtered = prev.filter((item) => item.message.role !== "system"); - return [ - ...filtered, - { - message: { role: "assistant" as const, content: "Response" }, - contextItems: [], - }, - ]; - }); - }); - - // Verify both React state and service were updated correctly - expect(result.current.chatHistory).toHaveLength(1); - expect(result.current.chatHistory[0].message.role).toBe("assistant"); - - const serviceHistory = chatHistoryService.getHistory(); - expect(serviceHistory).toHaveLength(1); - expect(serviceHistory[0].message.role).toBe("assistant"); - }); - - it("should clean up wrapper on unmount", async () => { - const { unmount } = renderHook(() => - useChat({ - model: undefined, - llmApi: mockLlmApi, - assistant: undefined, - onShowConfigSelector: vi.fn(), - onShowMCPSelector: vi.fn(), - }), - ); - - // Wait for initialization - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 100)); - }); - - // Unmount should cleanup without errors - expect(() => unmount()).not.toThrow(); - }); -}); \ No newline at end of file