Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix: prevent cross-tab chat conversation switching (#40709)

Joel84e348c52be9
diff --git a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
index 3d6a94b5f56..56d7a58ded6 100644
--- a/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/chat-with-history/__tests__/hooks.spec.tsx
@@ -17,7 +17,7 @@ import {
updateFeedback,
} from '@/service/share'
import { shareQueryKeys } from '@/service/use-share'
-import { CONVERSATION_ID_INFO } from '../../constants'
+import { CONVERSATION_ID_INFO, TAB_CONVERSATION_ID_INFO } from '../../constants'
import { useChatWithHistory } from '.././hooks'
vi.mock('@/hooks/use-app-favicon', () => ({
@@ -151,6 +151,7 @@ describe('useChatWithHistory', () => {
beforeEach(() => {
vi.clearAllMocks()
localStorage.removeItem(CONVERSATION_ID_INFO)
+ sessionStorage.removeItem(TAB_CONVERSATION_ID_INFO)
localStorage.removeItem('webappSidebarCollapse')
mockStoreState.appInfo = {
app_id: 'app-1',
@@ -169,6 +170,7 @@ describe('useChatWithHistory', () => {
afterEach(() => {
localStorage.removeItem(CONVERSATION_ID_INFO)
+ sessionStorage.removeItem(TAB_CONVERSATION_ID_INFO)
localStorage.removeItem('webappSidebarCollapse')
})
@@ -297,9 +299,86 @@ describe('useChatWithHistory', () => {
})
})
- // Scenario: conversation id updates persist to localStorage.
+ // Scenario: the active conversation is tab-scoped while the last selection is cross-tab.
describe('Conversation id persistence', () => {
- it('should store new conversation id in localStorage after completion', async () => {
+ it('should prefer the current tab conversation over the last conversation', async () => {
+ // Arrange
+ sessionStorage.setItem(
+ TAB_CONVERSATION_ID_INFO,
+ JSON.stringify({
+ 'app-1': {
+ 'user-1': 'conversation-in-this-tab',
+ DEFAULT: 'conversation-in-this-tab',
+ },
+ }),
+ )
+ mockFetchConversations.mockResolvedValue(createConversationData())
+ mockFetchChatList.mockResolvedValue({ data: [] })
+
+ // Act
+ const { result } = await renderWithClient(() => useChatWithHistory())
+
+ // Assert
+ expect(result!.current.currentConversationId).toBe('conversation-in-this-tab')
+ expect(mockFetchChatList).toHaveBeenCalledWith(
+ 'conversation-in-this-tab',
+ AppSourceType.webApp,
+ 'app-1',
+ )
+ })
+
+ it('should preserve a new chat selection in the current tab', async () => {
+ // Arrange
+ sessionStorage.setItem(
+ TAB_CONVERSATION_ID_INFO,
+ JSON.stringify({
+ 'app-1': {
+ 'user-1': '',
+ DEFAULT: '',
+ },
+ }),
+ )
+ mockFetchConversations.mockResolvedValue(createConversationData())
+ mockFetchChatList.mockResolvedValue({ data: [] })
+
+ // Act
+ const { result } = await renderWithClient(() => useChatWithHistory())
+
+ // Assert
+ expect(result!.current.currentConversationId).toBe('')
+ expect(mockFetchChatList).not.toHaveBeenCalled()
+ })
+
+ it('should ignore last conversation updates from another tab', async () => {
+ // Arrange
+ mockFetchConversations.mockResolvedValue(createConversationData())
+ mockFetchChatList.mockResolvedValue({ data: [] })
+ const { result } = await renderWithClient(() => useChatWithHistory())
+
+ await waitFor(() => {
+ expect(result!.current.currentConversationId).toBe('conversation-1')
+ })
+
+ // Act: storage events are delivered to the other tabs, not the tab that made the write.
+ act(() => {
+ setConversationIdInfo('app-1', 'conversation-from-another-tab')
+ window.dispatchEvent(
+ new StorageEvent('storage', {
+ key: CONVERSATION_ID_INFO,
+ }),
+ )
+ })
+
+ // Assert
+ expect(result!.current.currentConversationId).toBe('conversation-1')
+ expect(mockFetchChatList).not.toHaveBeenCalledWith(
+ 'conversation-from-another-tab',
+ AppSourceType.webApp,
+ 'app-1',
+ )
+ })
+
+ it('should store the current and last conversation after completion', async () => {
// Arrange
const listData = createConversationData({
data: [createConversationItem({ id: 'conversation-1', name: 'First' })],
@@ -319,11 +398,19 @@ describe('useChatWithHistory', () => {
// Assert
await waitFor(() => {
- const storedValue = localStorage.getItem(CONVERSATION_ID_INFO)
- const parsed = storedValue ? JSON.parse(storedValue) : {}
- const storedUserId = parsed['app-1']?.['user-1']
- const storedDefaultId = parsed['app-1']?.DEFAULT
- expect([storedUserId, storedDefaultId]).toContain('conversation-new')
+ const lastStoredValue = localStorage.getItem(CONVERSATION_ID_INFO)
+ const lastConversationIdInfo = lastStoredValue ? JSON.parse(lastStoredValue) : {}
+ const tabStoredValue = sessionStorage.getItem(TAB_CONVERSATION_ID_INFO)
+ const tabConversationIdInfo = tabStoredValue ? JSON.parse(tabStoredValue) : {}
+
+ expect([
+ lastConversationIdInfo['app-1']?.['user-1'],
+ lastConversationIdInfo['app-1']?.DEFAULT,
+ ]).toContain('conversation-new')
+ expect([
+ tabConversationIdInfo['app-1']?.['user-1'],
+ tabConversationIdInfo['app-1']?.DEFAULT,
+ ]).toContain('conversation-new')
})
})
})
diff --git a/web/app/components/base/chat/chat-with-history/hooks.tsx b/web/app/components/base/chat/chat-with-history/hooks.tsx
index 3fe556f0db2..e3bdb0374b2 100644
--- a/web/app/components/base/chat/chat-with-history/hooks.tsx
+++ b/web/app/components/base/chat/chat-with-history/hooks.tsx
@@ -9,7 +9,7 @@ import { produce } from 'immer'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
- useConversationIdInfo,
+ useConversationSelection,
useWebAppSidebarCollapseState,
} from '@/app/components/base/chat/storage'
import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
@@ -185,27 +185,10 @@ export const useChatWithHistory = (installedAppInfo?: InstalledAppResponse) => {
},
[appId, setStoredSidebarCollapseState],
)
- const [conversationIdInfo, setConversationIdInfo] = useConversationIdInfo()
- const currentConversationId = useMemo(
- () => conversationIdInfo?.[appId || '']?.[userId || 'DEFAULT'] || '',
- [appId, conversationIdInfo, userId],
- )
- const handleConversationIdInfoChange = useCallback(
- (changeConversationId: string) => {
- if (appId) {
- let prevValue = conversationIdInfo?.[appId || '']
- if (typeof prevValue === 'string') prevValue = {}
- setConversationIdInfo({
- ...conversationIdInfo,
- [appId || '']: {
- ...prevValue,
- [userId || 'DEFAULT']: changeConversationId,
- },
- })
- }
- },
- [appId, conversationIdInfo, setConversationIdInfo, userId],
- )
+ const { currentConversationId, handleConversationIdInfoChange } = useConversationSelection({
+ appId,
+ userId,
+ })
const [newConversationId, setNewConversationId] = useState('')
const chatShouldReloadKey = useMemo(() => {
if (currentConversationId === newConversationId) return ''
diff --git a/web/app/components/base/chat/constants.ts b/web/app/components/base/chat/constants.ts
index 309f0f04a71..7075c886dac 100644
--- a/web/app/components/base/chat/constants.ts
+++ b/web/app/components/base/chat/constants.ts
@@ -1,2 +1,3 @@
export const CONVERSATION_ID_INFO = 'conversationIdInfo'
+export const TAB_CONVERSATION_ID_INFO = 'tabConversationIdInfo'
export const UUID_NIL = '00000000-0000-0000-0000-000000000000'
diff --git a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
index 0c9082bfc49..0f022253500 100644
--- a/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/__tests__/hooks.spec.tsx
@@ -13,7 +13,7 @@ import {
} from '@/service/share'
import { shareQueryKeys } from '@/service/use-share'
import { TransferMethod } from '@/types/app'
-import { CONVERSATION_ID_INFO } from '../../constants'
+import { CONVERSATION_ID_INFO, TAB_CONVERSATION_ID_INFO } from '../../constants'
import { useEmbeddedChatbot } from '../hooks'
type InputForm = {
@@ -162,6 +162,7 @@ describe('useEmbeddedChatbot', () => {
mockGetProcessedSystemVariablesFromUrlParams.mockResolvedValue({})
mockGetProcessedUserVariablesFromUrlParams.mockResolvedValue({})
localStorage.removeItem(CONVERSATION_ID_INFO)
+ sessionStorage.removeItem(TAB_CONVERSATION_ID_INFO)
mockStoreState.appInfo = {
app_id: 'app-1',
custom_config: null,
@@ -182,6 +183,7 @@ describe('useEmbeddedChatbot', () => {
afterEach(() => {
localStorage.removeItem(CONVERSATION_ID_INFO)
+ sessionStorage.removeItem(TAB_CONVERSATION_ID_INFO)
})
// Scenario: share query results populate conversation lists and trigger chat list fetch.
@@ -367,9 +369,9 @@ describe('useEmbeddedChatbot', () => {
})
})
- // Scenario: conversation id updates persist to localStorage.
+ // Scenario: conversation id updates persist to tab and cross-tab storage.
describe('Conversation id persistence', () => {
- it('should store new conversation id in localStorage after completion', async () => {
+ it('should store the current and last conversation after completion', async () => {
// Arrange
const listData = createConversationData({
data: [createConversationItem({ id: 'conversation-1', name: 'First' })],
@@ -389,11 +391,19 @@ describe('useEmbeddedChatbot', () => {
// Assert
await waitFor(() => {
- const storedValue = localStorage.getItem(CONVERSATION_ID_INFO)
- const parsed = storedValue ? JSON.parse(storedValue) : {}
- const storedUserId = parsed['app-1']?.['embedded-user-1']
- const storedDefaultId = parsed['app-1']?.DEFAULT
- expect([storedUserId, storedDefaultId]).toContain('conversation-new')
+ const lastStoredValue = localStorage.getItem(CONVERSATION_ID_INFO)
+ const lastConversationIdInfo = lastStoredValue ? JSON.parse(lastStoredValue) : {}
+ const tabStoredValue = sessionStorage.getItem(TAB_CONVERSATION_ID_INFO)
+ const tabConversationIdInfo = tabStoredValue ? JSON.parse(tabStoredValue) : {}
+
+ expect([
+ lastConversationIdInfo['app-1']?.['embedded-user-1'],
+ lastConversationIdInfo['app-1']?.DEFAULT,
+ ]).toContain('conversation-new')
+ expect([
+ tabConversationIdInfo['app-1']?.['embedded-user-1'],
+ tabConversationIdInfo['app-1']?.DEFAULT,
+ ]).toContain('conversation-new')
})
})
})
@@ -434,6 +444,10 @@ describe('useEmbeddedChatbot', () => {
CONVERSATION_ID_INFO,
JSON.stringify({ 'app-1': { 'user-1': 'conv-id' } }),
)
+ sessionStorage.setItem(
+ TAB_CONVERSATION_ID_INFO,
+ JSON.stringify({ 'app-1': { 'user-1': 'conv-id' } }),
+ )
const { result } = await renderWithClient(() => useEmbeddedChatbot(AppSourceType.webApp))
@@ -445,6 +459,9 @@ describe('useEmbeddedChatbot', () => {
const storedValue = localStorage.getItem(CONVERSATION_ID_INFO)
const parsed = storedValue ? JSON.parse(storedValue) : {}
expect(parsed['app-1']).toBeUndefined()
+ const tabStoredValue = sessionStorage.getItem(TAB_CONVERSATION_ID_INFO)
+ const tabParsed = tabStoredValue ? JSON.parse(tabStoredValue) : {}
+ expect(Object.values(tabParsed['app-1'] ?? {})).toContain('')
})
})
})
diff --git a/web/app/components/base/chat/embedded-chatbot/hooks.tsx b/web/app/components/base/chat/embedded-chatbot/hooks.tsx
index 991c4760a89..0c7950f562c 100644
--- a/web/app/components/base/chat/embedded-chatbot/hooks.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/hooks.tsx
@@ -8,7 +8,7 @@ import { noop } from 'es-toolkit/function'
import { produce } from 'immer'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { useConversationIdInfo } from '@/app/components/base/chat/storage'
+import { useConversationSelection } from '@/app/components/base/chat/storage'
import { addFileInfos, sortAgentSorts } from '@/app/components/tools/utils'
import { InputVarType } from '@/app/components/workflow/types'
import { useWebAppStore } from '@/context/web-app-context'
@@ -118,38 +118,9 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri
}
setLanguageFromParams()
}, [appInfo])
- const [conversationIdInfo, setConversationIdInfo] = useConversationIdInfo()
- const removeConversationIdInfo = useCallback(
- (appId: string) => {
- setConversationIdInfo((prev) => {
- const newInfo = { ...prev }
- delete newInfo[appId]
- return newInfo
- })
- },
- [setConversationIdInfo],
- )
const allowResetChat = !conversationId
- const currentConversationId = useMemo(
- () => conversationId || conversationIdInfo?.[appId || '']?.[userId || 'DEFAULT'] || '',
- [appId, conversationIdInfo, userId, conversationId],
- )
- const handleConversationIdInfoChange = useCallback(
- (changeConversationId: string) => {
- if (appId) {
- let prevValue = conversationIdInfo?.[appId || '']
- if (typeof prevValue === 'string') prevValue = {}
- setConversationIdInfo({
- ...conversationIdInfo,
- [appId || '']: {
- ...prevValue,
- [userId || 'DEFAULT']: changeConversationId,
- },
- })
- }
- },
- [appId, conversationIdInfo, setConversationIdInfo, userId],
- )
+ const { currentConversationId, handleConversationIdInfoChange, removeConversationIdInfo } =
+ useConversationSelection({ appId, userId, conversationId })
const [newConversationId, setNewConversationId] = useState('')
const chatShouldReloadKey = useMemo(() => {
if (currentConversationId === newConversationId) return ''
diff --git a/web/app/components/base/chat/storage.ts b/web/app/components/base/chat/storage.ts
index 5b1bd7c0e75..ea7e65733da 100644
--- a/web/app/components/base/chat/storage.ts
+++ b/web/app/components/base/chat/storage.ts
@@ -1,8 +1,15 @@
import { createLocalStorageState } from 'foxact/create-local-storage-state'
-import { CONVERSATION_ID_INFO } from './constants'
+import { createSessionStorageState } from 'foxact/create-session-storage-state'
+import { useCallback, useEffect } from 'react'
+import { CONVERSATION_ID_INFO, TAB_CONVERSATION_ID_INFO } from './constants'
-const [useConversationIdInfo, _useConversationIdInfoValue, _useSetConversationIdInfo] =
- createLocalStorageState<Record<string, Record<string, string>>>(CONVERSATION_ID_INFO, {})
+type ConversationIdInfo = Record<string, Record<string, string>>
+
+const [useLastConversationIdInfo, _useLastConversationIdInfoValue, _useSetLastConversationIdInfo] =
+ createLocalStorageState<ConversationIdInfo>(CONVERSATION_ID_INFO, {})
+
+const [useTabConversationIdInfo, _useTabConversationIdInfoValue, _useSetTabConversationIdInfo] =
+ createSessionStorageState<ConversationIdInfo>(TAB_CONVERSATION_ID_INFO, {})
const [
useWebAppSidebarCollapseState,
@@ -10,4 +17,124 @@ const [
_useSetWebAppSidebarCollapseState,
] = createLocalStorageState<string>('webappSidebarCollapse', undefined, { raw: true })
-export { useConversationIdInfo, useWebAppSidebarCollapseState }
+const getAppConversationIds = (conversationIdInfo: ConversationIdInfo | null, appId: string) => {
+ const appConversationIds = conversationIdInfo?.[appId]
+ return typeof appConversationIds === 'object' && appConversationIds !== null
+ ? appConversationIds
+ : undefined
+}
+
+const hasConversationId = (
+ conversationIdInfo: ConversationIdInfo | null,
+ appId: string,
+ userId: string,
+) => Object.hasOwn(getAppConversationIds(conversationIdInfo, appId) ?? {}, userId)
+
+const getConversationId = (
+ conversationIdInfo: ConversationIdInfo | null,
+ appId: string,
+ userId: string,
+) => getAppConversationIds(conversationIdInfo, appId)?.[userId] ?? ''
+
+const setConversationId = (
+ conversationIdInfo: ConversationIdInfo | null,
+ appId: string,
+ userId: string,
+ conversationId: string,
+): ConversationIdInfo => ({
+ ...(conversationIdInfo ?? {}),
+ [appId]: {
+ ...getAppConversationIds(conversationIdInfo, appId),
+ [userId]: conversationId,
+ },
+})
+
+const removeAppConversationIds = (
+ conversationIdInfo: ConversationIdInfo | null,
+ appId: string,
+): ConversationIdInfo => {
+ const nextConversationIdInfo = { ...(conversationIdInfo ?? {}) }
+ delete nextConversationIdInfo[appId]
+ return nextConversationIdInfo
+}
+
+type UseConversationSelectionOptions = {
+ appId?: string
+ userId?: string
+ conversationId?: string
+}
+
+const useConversationSelection = ({
+ appId,
+ userId,
+ conversationId,
+}: UseConversationSelectionOptions) => {
+ const [lastConversationIdInfo, setLastConversationIdInfo] = useLastConversationIdInfo()
+ const [tabConversationIdInfo, setTabConversationIdInfo] = useTabConversationIdInfo()
+ const storageAppId = appId ?? ''
+ const storageUserId = userId || 'DEFAULT'
+ const hasTabConversationId =
+ !!appId && hasConversationId(tabConversationIdInfo, storageAppId, storageUserId)
+ const lastConversationId = appId
+ ? getConversationId(lastConversationIdInfo, storageAppId, storageUserId)
+ : ''
+ const tabConversationId = appId
+ ? getConversationId(tabConversationIdInfo, storageAppId, storageUserId)
+ : ''
+
+ // Seed this tab once from the cross-tab last selection. Later localStorage updates can change
+ // the fallback without changing the active conversation already owned by this tab.
+ useEffect(() => {
+ if (!appId || hasTabConversationId) return
+
+ setTabConversationIdInfo((currentConversationIdInfo) => {
+ if (hasConversationId(currentConversationIdInfo, appId, storageUserId))
+ return currentConversationIdInfo
+
+ return setConversationId(currentConversationIdInfo, appId, storageUserId, lastConversationId)
+ })
+ }, [appId, hasTabConversationId, lastConversationId, setTabConversationIdInfo, storageUserId])
+
+ const handleConversationIdInfoChange = useCallback(
+ (nextConversationId: string) => {
+ if (!appId) return
+
+ setTabConversationIdInfo((currentConversationIdInfo) =>
+ setConversationId(currentConversationIdInfo, appId, storageUserId, nextConversationId),
+ )
+ setLastConversationIdInfo((currentConversationIdInfo) =>
+ setConversationId(currentConversationIdInfo, appId, storageUserId, nextConversationId),
+ )
+ },
+ [appId, setLastConversationIdInfo, setTabConversationIdInfo, storageUserId],
+ )
+
+ const removeConversationIdInfo = useCallback(
+ (targetAppId: string) => {
+ setTabConversationIdInfo((currentConversationIdInfo) => {
+ const nextConversationIdInfo = removeAppConversationIds(
+ currentConversationIdInfo,
+ targetAppId,
+ )
+ if (targetAppId !== appId) return nextConversationIdInfo
+
+ // An explicit empty entry keeps this tab on New Chat instead of falling back to a last
+ // conversation that another tab may write after the reset.
+ return setConversationId(nextConversationIdInfo, targetAppId, storageUserId, '')
+ })
+ setLastConversationIdInfo((currentConversationIdInfo) =>
+ removeAppConversationIds(currentConversationIdInfo, targetAppId),
+ )
+ },
+ [appId, setLastConversationIdInfo, setTabConversationIdInfo, storageUserId],
+ )
+
+ return {
+ currentConversationId:
+ conversationId || (hasTabConversationId ? tabConversationId : lastConversationId),
+ handleConversationIdInfoChange,
+ removeConversationIdInfo,
+ }
+}
+
+export { useConversationSelection, useWebAppSidebarCollapseState }