From 4935eeff282f81c070417872b27813f2203b418d Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Mon, 17 Aug 2026 20:47:57 +0800 Subject: [PATCH] fix(webui): preserve selected chatbot agent preference on reload (#323) --- .../webui/components/chatbot-sidebar.test.tsx | 193 ++++++++++++++++++ packages/webui/components/chatbot-sidebar.tsx | 6 +- 2 files changed, 197 insertions(+), 2 deletions(-) create mode 100644 packages/webui/components/chatbot-sidebar.test.tsx diff --git a/packages/webui/components/chatbot-sidebar.test.tsx b/packages/webui/components/chatbot-sidebar.test.tsx new file mode 100644 index 00000000..bebc1040 --- /dev/null +++ b/packages/webui/components/chatbot-sidebar.test.tsx @@ -0,0 +1,193 @@ +// @vitest-environment happy-dom +import { cleanup, render, waitFor } from '@testing-library/react' +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { ChatbotSidebar } from './chatbot-sidebar' +import { useChatbotStore, AGENT_PREFERENCE_STORAGE_KEY } from '@/ui/stores/chatbot' +import { client } from '@/ui/api/client' + +const localStorageMock = (() => { + let store: Record = {} + return { + getItem: (key: string) => store[key] || null, + setItem: (key: string, value: string) => { + store[key] = value.toString() + }, + removeItem: (key: string) => { + delete store[key] + }, + clear: () => { + store = {} + }, + } +})() + +if (typeof globalThis.localStorage === 'undefined') { + Object.defineProperty(globalThis, 'localStorage', { + value: localStorageMock, + }) +} +if (typeof globalThis.window === 'undefined') { + Object.defineProperty(globalThis, 'window', { + value: globalThis, + }) +} + +// Mock droppable from @dnd-kit/react +vi.mock('@dnd-kit/react', () => ({ + useDroppable: () => ({ + ref: vi.fn(), + isDropTarget: false, + }), +})) + +// Mock API client +vi.mock('@/ui/api/client', () => ({ + client: { + api: { + projects: { + ':projectId': { + 'chat-agents': { + $get: vi.fn(), + }, + }, + }, + teams: { + ':teamId': { + chat: { + sessions: { + $get: vi.fn(() => + Promise.resolve({ + ok: true, + json: async () => ({ data: [] }), + } as unknown), + ), + }, + }, + }, + }, + }, + }, +})) + +describe('ChatbotSidebar - Agent Selection & Preference Persistence', () => { + let queryClient: QueryClient + + beforeEach(() => { + queryClient = new QueryClient({ + defaultOptions: { + queries: { + retry: false, + }, + }, + }) + localStorage.clear() + useChatbotStore.setState({ + isHistoryMode: false, + isChatbotOpen: true, + currentSessionId: null, + chatAssets: [], + messages: [], + historySessions: [], + isStreaming: false, + selectedAgentId: null, + inputText: '', + }) + }) + + afterEach(() => { + cleanup() + vi.clearAllMocks() + }) + + it('should not wipe saved agent preference while chat agents query is loading', async () => { + localStorage.setItem(AGENT_PREFERENCE_STORAGE_KEY, 'agent-2') + useChatbotStore.setState({ selectedAgentId: 'agent-2' }) + + let resolveAgents: (value: unknown) => void + const agentsPromise = new Promise((resolve) => { + resolveAgents = resolve + }) + + vi.mocked(client.api.projects[':projectId']['chat-agents'].$get).mockImplementation( + () => + agentsPromise as unknown as ReturnType< + (typeof client.api.projects)[':projectId']['chat-agents']['$get'] + >, + ) + + render( + + + , + ) + + // While query is loading, selectedAgentId in store and localStorage must NOT be wiped + expect(useChatbotStore.getState().selectedAgentId).toBe('agent-2') + expect(localStorage.getItem(AGENT_PREFERENCE_STORAGE_KEY)).toBe('agent-2') + + // Now resolve query with available agents + resolveAgents!({ + ok: true, + json: async () => [ + { id: 'agent-1', name: 'Agent 1', type: 'chat', enabled: true }, + { id: 'agent-2', name: 'Agent 2', type: 'chat', enabled: true }, + ], + }) + + await waitFor(() => { + expect(useChatbotStore.getState().selectedAgentId).toBe('agent-2') + expect(localStorage.getItem(AGENT_PREFERENCE_STORAGE_KEY)).toBe('agent-2') + }) + }) + + it('should fallback to first agent if saved agent does not exist in project agents list', async () => { + localStorage.setItem(AGENT_PREFERENCE_STORAGE_KEY, 'agent-nonexistent') + useChatbotStore.setState({ selectedAgentId: 'agent-nonexistent' }) + + vi.mocked(client.api.projects[':projectId']['chat-agents'].$get).mockResolvedValue({ + ok: true, + json: async () => [ + { id: 'agent-1', name: 'Agent 1', type: 'chat', enabled: true }, + { id: 'agent-2', name: 'Agent 2', type: 'chat', enabled: true }, + ], + } as unknown as Awaited< + ReturnType<(typeof client.api.projects)[':projectId']['chat-agents']['$get']> + >) + + render( + + + , + ) + + await waitFor(() => { + expect(useChatbotStore.getState().selectedAgentId).toBe('agent-1') + expect(localStorage.getItem(AGENT_PREFERENCE_STORAGE_KEY)).toBe('agent-1') + }) + }) + + it('should reset to null if project has no enabled chat agents', async () => { + localStorage.setItem(AGENT_PREFERENCE_STORAGE_KEY, 'agent-1') + useChatbotStore.setState({ selectedAgentId: 'agent-1' }) + + vi.mocked(client.api.projects[':projectId']['chat-agents'].$get).mockResolvedValue({ + ok: true, + json: async () => [], + } as unknown as Awaited< + ReturnType<(typeof client.api.projects)[':projectId']['chat-agents']['$get']> + >) + + render( + + + , + ) + + await waitFor(() => { + expect(useChatbotStore.getState().selectedAgentId).toBeNull() + expect(localStorage.getItem(AGENT_PREFERENCE_STORAGE_KEY)).toBeNull() + }) + }) +}) diff --git a/packages/webui/components/chatbot-sidebar.tsx b/packages/webui/components/chatbot-sidebar.tsx index 6ae469ee..323482c2 100644 --- a/packages/webui/components/chatbot-sidebar.tsx +++ b/packages/webui/components/chatbot-sidebar.tsx @@ -65,7 +65,7 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp } }, [projectId, ensureTeamIdForProject]) - const { data: agents = [] } = useQuery({ + const { data: agents = [], isSuccess } = useQuery({ queryKey: ['chat-agents', projectId], queryFn: async () => { if (!projectId) return [] @@ -81,6 +81,8 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp const chatAgents = agents.filter((a) => a.type === 'chat' && a.enabled) useEffect(() => { + if (!isSuccess) return + if (chatAgents.length > 0) { const exists = chatAgents.some((a) => a.id === selectedAgentId) if (!exists) { @@ -89,7 +91,7 @@ export function ChatbotSidebar({ projectId, contextAssetId }: ChatbotSidebarProp } else if (selectedAgentId !== null) { setSelectedAgentId(null) } - }, [chatAgents, selectedAgentId, setSelectedAgentId]) + }, [isSuccess, chatAgents, selectedAgentId, setSelectedAgentId]) const messagesEndRef = useRef(null) const scrollAreaRef = useRef(null)