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.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(workflow): own preview chat requests with Console Query (#44136)
yyh09d9a015356a
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 84afe06531e..4f4e5f4c12f 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -3589,15 +3589,7 @@"count": 2}},- "web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsx": {- "dify/no-app-store-imports": {- "count": 1- }- },"web/app/components/workflow/panel/chat-record/index.tsx": {- "dify/no-app-store-imports": {- "count": 1- },"jsx-a11y/click-events-have-key-events": {"count": 1},@@ -3605,7 +3597,7 @@"count": 1},"typescript/no-explicit-any": {- "count": 8+ "count": 7}},"web/app/components/workflow/panel/chat-record/user-input.tsx": {@@ -3658,16 +3650,6 @@"count": 3}},- "web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx": {- "dify/no-app-store-imports": {- "count": 1- }- },- "web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx": {- "dify/no-app-store-imports": {- "count": 1- }- },"web/app/components/workflow/panel/debug-and-preview/__tests__/hooks.spec.ts": {"no-restricted-imports": {"count": 1@@ -3675,7 +3657,7 @@},"web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts": {"typescript/no-explicit-any": {- "count": 69+ "count": 68}},"web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-send.spec.ts": {@@ -3685,7 +3667,7 @@},"web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts": {"typescript/no-explicit-any": {- "count": 15+ "count": 13}},"web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/misc.spec.ts": {@@ -3704,9 +3686,6 @@}},"web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx": {- "dify/no-app-store-imports": {- "count": 1- },"typescript/no-explicit-any": {"count": 5}@@ -3721,7 +3700,7 @@"count": 2},"typescript/no-explicit-any": {- "count": 11+ "count": 8}},"web/app/components/workflow/panel/debug-and-preview/user-input.tsx": {diff --git a/web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsx b/web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsxindex 6516e4a225c..3ddb5175827 100644--- a/web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsx+++ b/web/app/components/workflow/panel/chat-record/__tests__/index.spec.tsx@@ -1,17 +1,20 @@import type { HistoryWorkflowData } from '@/app/components/workflow/types'-import { screen, waitFor } from '@testing-library/react'+import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { useStore as useAppStore } from '@/app/components/app/store'import { renderWorkflowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'-import { fetchConversationMessages } from '@/service/debug'-import { createAppDetailFixture } from '@/test/fixtures/app'import ChatRecord from '../index'-vi.mock('@/service/debug', () => ({- fetchConversationMessages: vi.fn(),+const routeParams = vi.hoisted(() => ({ appId: 'app-1' }))+const mockRequest = vi.hoisted(() => vi.fn())++vi.mock('@/next/navigation', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/next/navigation')>()),+ useParams: () => routeParams,}))-const mockFetchConversationMessages = vi.mocked(fetchConversationMessages)+vi.mock('@/service/console/browser', () => ({+ consoleBrowserLink: { call: mockRequest },+}))const historyWorkflowData: HistoryWorkflowData = {id: 'run-1',@@ -22,16 +25,14 @@ const historyWorkflowData: HistoryWorkflowData = {describe('ChatRecord', () => {beforeEach(() => {- vi.clearAllMocks()- useAppStore.setState({- appDetail: createAppDetailFixture(),- })+ routeParams.appId = 'app-1'+ mockRequest.mockReset()})- it('renders fetched chat history with the real chat shell and switches siblings', async () => {+ it('renders chat history and keeps sibling selection within its conversation', async () => {const user = userEvent.setup()- mockFetchConversationMessages.mockResolvedValue({+ mockRequest.mockResolvedValue({data: [{id: 'msg-1',@@ -59,7 +60,7 @@ describe('ChatRecord', () => {],} as never)- renderWorkflowComponent(<ChatRecord />, {+ const { store } = renderWorkflowComponent(<ChatRecord />, {initialStoreState: { historyWorkflowData },hooksStoreProps: {handleLoadBackupDraft: vi.fn(),@@ -67,7 +68,11 @@ describe('ChatRecord', () => {})await waitFor(() => {- expect(mockFetchConversationMessages).toHaveBeenCalledWith('app-1', 'conversation-1')+ expect(mockRequest).toHaveBeenCalledWith(+ ['apps', 'byAppId', 'chatMessages', 'get'],+ { params: { app_id: 'app-1' }, query: { conversation_id: 'conversation-1' } },+ expect.any(Object),+ )})expect(await screen.findByText('Question 1')).toBeInTheDocument()@@ -84,10 +89,64 @@ describe('ChatRecord', () => {await waitFor(() => {expect(screen.queryByText('Question 3')).not.toBeInTheDocument()})++ act(() => {+ store.setState({+ historyWorkflowData: { ...historyWorkflowData, conversation_id: 'conversation-2' },+ })+ })+ expect(await screen.findByText('Question 3')).toBeInTheDocument()+ expect(screen.queryByText('Question 2')).not.toBeInTheDocument()+ expect(mockRequest).toHaveBeenLastCalledWith(+ ['apps', 'byAppId', 'chatMessages', 'get'],+ { params: { app_id: 'app-1' }, query: { conversation_id: 'conversation-2' } },+ expect.any(Object),+ )+ })++ it('keeps a late response from a previous app out of the current conversation', async () => {+ let resolvePrevious!: (value: unknown) => void+ mockRequest.mockReturnValueOnce(+ new Promise((resolve) => {+ resolvePrevious = resolve+ }),+ )+ mockRequest.mockResolvedValue({+ data: [{ id: 'message-2', query: 'Current question', answer: 'Current answer' }],+ has_more: false,+ limit: 20,+ })+ const { store } = renderWorkflowComponent(<ChatRecord />, {+ initialStoreState: { historyWorkflowData },+ })+ await waitFor(() => expect(mockRequest).toHaveBeenCalledTimes(1))++ routeParams.appId = 'app-2'+ act(() => {+ store.setState({+ historyWorkflowData: { ...historyWorkflowData, conversation_id: 'conversation-2' },+ })+ })+ expect(await screen.findByText('Current answer')).toBeInTheDocument()+ expect(mockRequest).toHaveBeenLastCalledWith(+ ['apps', 'byAppId', 'chatMessages', 'get'],+ { params: { app_id: 'app-2' }, query: { conversation_id: 'conversation-2' } },+ expect.any(Object),+ )++ await act(async () => {+ resolvePrevious({+ data: [{ id: 'message-1', query: 'Previous question', answer: 'Previous answer' }],+ has_more: false,+ limit: 20,+ })+ })+ expect(screen.queryByText('Previous answer')).not.toBeInTheDocument()+ expect(screen.getByText('Current answer')).toBeInTheDocument()})it('stops loading when conversation fetching fails', async () => {- mockFetchConversationMessages.mockRejectedValue(new Error('network error'))+ mockRequest.mockRejectedValue(new Error('network error'))const { container } = renderWorkflowComponent(<ChatRecord />, {initialStoreState: { historyWorkflowData },diff --git a/web/app/components/workflow/panel/chat-record/index.tsx b/web/app/components/workflow/panel/chat-record/index.tsxindex b25745ff848..ef661afdd85 100644--- a/web/app/components/workflow/panel/chat-record/index.tsx+++ b/web/app/components/workflow/panel/chat-record/index.tsx@@ -1,13 +1,14 @@import type { IChatItem } from '@/app/components/base/chat/chat/type'-import type { ChatItem, ChatItemInTree } from '@/app/components/base/chat/types'+import type { ChatItem } from '@/app/components/base/chat/types'import { RiCloseLine } from '@remixicon/react'-import { memo, useCallback, useEffect, useState } from 'react'-import { useStore as useAppStore } from '@/app/components/app/store'+import { skipToken, useQuery } from '@tanstack/react-query'+import { memo, useMemo, useState } from 'react'import Chat from '@/app/components/base/chat/chat'import { buildChatItemTree, getThreadMessages } from '@/app/components/base/chat/utils'import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'-import { fetchConversationMessages } from '@/service/debug'+import { useParams } from '@/next/navigation'+import { consoleQuery } from '@/service/console'import { useWorkflowRun } from '../../hooks/use-workflow-run'import { useStore, useWorkflowStore } from '../../store'import { formatWorkflowRunIdentifier } from '../../utils'@@ -48,44 +49,34 @@ function getFormattedChatList(messages: any[]) {}const ChatRecord = () => {- const [fetched, setFetched] = useState(false)- const [chatItemTree, setChatItemTree] = useState<ChatItemInTree[]>([])- const [threadChatItems, setThreadChatItems] = useState<IChatItem[]>([])- const appDetail = useAppStore((s) => s.appDetail)+ const { appId } = useParams<{ appId: string }>()+ const [selectedMessage, setSelectedMessage] = useState<{+ appId: string+ conversationId: string | undefined+ messageId: string+ }>()const workflowStore = useWorkflowStore()const setMessageLogItem = useStore((state) => state.setMessageLogItem)const { handleLoadBackupDraft } = useWorkflowRun()const historyWorkflowData = useStore((s) => s.historyWorkflowData)const currentConversationID = historyWorkflowData?.conversation_id- const handleFetchConversationMessages = useCallback(async () => {- if (appDetail && currentConversationID) {- try {- setFetched(false)- const res = await fetchConversationMessages(appDetail.id, currentConversationID)-- const newAllChatItems = getFormattedChatList((res as any).data)-- const tree = buildChatItemTree(newAllChatItems)- setChatItemTree(tree)- setThreadChatItems(getThreadMessages(tree, newAllChatItems.at(-1)?.id))- } catch {- } finally {- setFetched(true)- }- }- }, [appDetail, currentConversationID])-- useEffect(() => {- handleFetchConversationMessages()- }, [currentConversationID, appDetail, handleFetchConversationMessages])-- const switchSibling = useCallback(- (siblingMessageId: string) => {- setThreadChatItems(getThreadMessages(chatItemTree, siblingMessageId))- },- [chatItemTree],+ const { data, isPending } = useQuery(+ consoleQuery.apps.byAppId.chatMessages.get.queryOptions({+ input: currentConversationID+ ? { params: { app_id: appId }, query: { conversation_id: currentConversationID } }+ : skipToken,+ retry: false,+ refetchOnWindowFocus: false,+ }),)+ const chatItems = useMemo(() => getFormattedChatList(data?.data ?? []), [data])+ const chatItemTree = useMemo(() => buildChatItemTree(chatItems), [chatItems])+ const selectedMessageId =+ selectedMessage?.appId === appId && selectedMessage.conversationId === currentConversationID+ ? selectedMessage.messageId+ : chatItems.at(-1)?.id+ const threadChatItems: IChatItem[] = getThreadMessages(chatItemTree, selectedMessageId)return (<div@@ -94,12 +85,12 @@ const ChatRecord = () => {// background: 'linear-gradient(156deg, rgba(242, 244, 247, 0.80) 0%, rgba(242, 244, 247, 0.00) 99.43%), var(--white, #FFF)',// }}>- {!fetched && (+ {isPending && (<div className="flex h-full items-center justify-center"><LoadingPlaceholder /></div>)}- {fetched && (+ {!isPending && (<><div className="flex shrink-0 items-center justify-between p-4 pb-1 text-base font-semibold text-text-primary">{`TEST CHAT${formatWorkflowRunIdentifier(historyWorkflowData?.finished_at)}`}@@ -134,7 +125,9 @@ const ChatRecord = () => {allToolIcons={{}}onOpenLog={setMessageLogItem}canOpenLog={(item) => !!item.workflow_run_id}- switchSibling={switchSibling}+ switchSibling={(messageId) =>+ setSelectedMessage({ appId, conversationId: currentConversationID, messageId })+ }noSpacingchatAnswerContainerInner="pr-2!"/>diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsxindex b7febabf7ea..7e769acb35d 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/chat-wrapper.spec.tsx@@ -4,20 +4,25 @@ import type { IChatItem } from '@/app/components/base/chat/chat/type'import type { SpeechToTextTarget } from '@/app/components/base/voice-input/types'import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { useStore as useAppStore } from '@/app/components/app/store'import { createStartNode } from '@/app/components/workflow/__tests__/fixtures'import { renderWorkflowFlowComponent } from '@/app/components/workflow/__tests__/workflow-test-env'import { InputVarType } from '@/app/components/workflow/types'import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'-import { fetchSuggestedQuestions, stopChatMessageResponding } from '@/service/debug'import ChatWrapper from '../chat-wrapper'const mockUseChat = vi.hoisted(() => vi.fn())const mockUseSubscription = vi.hoisted(() => vi.fn())-vi.mock('@/service/debug', () => ({- fetchSuggestedQuestions: vi.fn(),- stopChatMessageResponding: vi.fn(),+const routeParams = vi.hoisted(() => ({ appId: 'app-1' }))+const mockRequest = vi.hoisted(() => vi.fn())++vi.mock('@/next/navigation', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/next/navigation')>()),+ useParams: () => routeParams,+}))++vi.mock('@/service/console/browser', () => ({+ consoleBrowserLink: { call: mockRequest },}))vi.mock('@/app/components/base/chat/chat', () => ({@@ -139,9 +144,6 @@ vi.mock('@/context/event-emitter', () => ({}),}))-const mockFetchSuggestedQuestions = vi.mocked(fetchSuggestedQuestions)-const mockStopChatMessageResponding = vi.mocked(stopChatMessageResponding)-const createChatState = (overrides: Record<string, unknown> = {}) => ({conversationId: 'conversation-1',chatList: [],@@ -162,15 +164,9 @@ const createChatWrapperRef = () =>describe('ChatWrapper', () => {beforeEach(() => {vi.clearAllMocks()- useAppStore.setState({- appDetail: {- id: 'app-1',- site: {- access_token: 'site-token',- app_base_url: 'https://example.com',- },- } as ReturnType<typeof useAppStore.getState>['appDetail'],- })+ routeParams.appId = 'app-1'+ mockRequest.mockReset()+ mockRequest.mockResolvedValue({ data: [] })mockUseChat.mockReturnValue(createChatState())})@@ -329,16 +325,13 @@ describe('ChatWrapper', () => {)const sendCallbacks = handleSend.mock.calls[0]?.[1] as {- onGetSuggestedQuestions: (- messageId: string,- getAbortController: () => AbortController,- ) => void+ onGetSuggestedQuestions: (messageId: string, onCancel: (cancel: () => void) => void) => void}- sendCallbacks.onGetSuggestedQuestions('message-1', () => new AbortController())- expect(mockFetchSuggestedQuestions).toHaveBeenCalledWith(- 'app-1',- 'message-1',- expect.any(Function),+ await sendCallbacks.onGetSuggestedQuestions('message-1', () => {})+ expect(mockRequest).toHaveBeenCalledWith(+ ['apps', 'byAppId', 'chatMessages', 'byMessageId', 'suggestedQuestions', 'get'],+ { params: { app_id: 'app-1', message_id: 'message-1' } },+ expect.objectContaining({ signal: expect.any(AbortSignal) }),)await user.click(screen.getByRole('button', { name: 'regenerate-chat' }))@@ -360,8 +353,12 @@ describe('ChatWrapper', () => {)const stopResponding = mockUseChat.mock.calls[0]?.[3] as (taskId: string) => void- stopResponding('task-1')- expect(mockStopChatMessageResponding).toHaveBeenCalledWith('app-1', 'task-1')+ await stopResponding('task-1')+ expect(mockRequest).toHaveBeenCalledWith(+ ['apps', 'byAppId', 'chatMessages', 'byTaskId', 'stop', 'post'],+ { params: { app_id: 'app-1', task_id: 'task-1' } },+ expect.any(Object),+ )await user.click(screen.getByRole('button', { name: 'submit-human-input' }))await waitFor(() => {@@ -381,6 +378,48 @@ describe('ChatWrapper', () => {expect(handleStop).toHaveBeenCalledTimes(1)})+ it('cancels only the requested message query through the chat cancellation callback', async () => {+ const user = userEvent.setup()+ const handleSend = vi.fn()+ mockUseChat.mockReturnValue(createChatState({ handleSend }))+ mockRequest.mockImplementation(() => new Promise(() => {}))++ renderWorkflowFlowComponent(+ <ChatWrapper+ ref={createChatWrapperRef()}+ showConversationVariableModal={false}+ onConversationModalHide={vi.fn()}+ showInputsFieldsPanel={false}+ onHide={vi.fn()}+ />,+ { nodes: [createStartNode()], edges: [] },+ )+ await user.click(screen.getByRole('button', { name: 'send-chat' }))+ const { onGetSuggestedQuestions } = handleSend.mock.calls[0]![1] as {+ onGetSuggestedQuestions: (+ messageId: string,+ onCancel: (cancel: () => void) => void,+ ) => Promise<unknown>+ }+ const onCancelFirst = vi.fn()+ const onCancelSecond = vi.fn()+ const firstRequest = onGetSuggestedQuestions('message-1', onCancelFirst)+ const firstCancelled = expect(firstRequest).rejects.toThrow()+ const secondRequest = onGetSuggestedQuestions('message-2', onCancelSecond)+ const secondCancelled = expect(secondRequest).rejects.toThrow()++ await waitFor(() => expect(mockRequest).toHaveBeenCalledTimes(2))+ const firstSignal = mockRequest.mock.calls[0]![2].signal as AbortSignal+ const secondSignal = mockRequest.mock.calls[1]![2].signal as AbortSignal+ onCancelFirst.mock.calls[0]![0]()+ await firstCancelled+ expect(firstSignal.aborted).toBe(true)+ expect(secondSignal.aborted).toBe(false)++ onCancelSecond.mock.calls[0]![0]()+ await secondCancelled+ })+it('collapses the side panel while the chat is responding', async () => {const onHide = vi.fn()mockUseChat.mockReturnValue(diff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx b/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsxindex 5ee5a4f47b7..c7ad62eb3d2 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/components.spec.tsx@@ -4,7 +4,6 @@ import type { ConversationVariable } from '@/app/components/workflow/types'import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import copy from 'copy-to-clipboard'-import { useStore as useAppStore } from '@/app/components/app/store'import { createStartNode } from '@/app/components/workflow/__tests__/fixtures'import {renderWorkflowComponent,@@ -13,7 +12,6 @@ import {import { ChatVarType } from '@/app/components/workflow/panel/chat-variable-panel/type'import { InputVarType } from '@/app/components/workflow/types'import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'-import { fetchSuggestedQuestions, stopChatMessageResponding } from '@/service/debug'import { fetchCurrentValueOfConversationVariable } from '@/service/workflow'import ChatWrapper from '../chat-wrapper'import ConversationVariableModal from '../conversation-variable-modal'@@ -27,9 +25,16 @@ vi.mock('copy-to-clipboard', () => ({default: vi.fn(),}))-vi.mock('@/service/debug', () => ({- fetchSuggestedQuestions: vi.fn(),- stopChatMessageResponding: vi.fn(),+const routeParams = vi.hoisted(() => ({ appId: 'app-1' }))+const mockRequest = vi.hoisted(() => vi.fn())++vi.mock('@/next/navigation', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@/next/navigation')>()),+ useParams: () => routeParams,+}))++vi.mock('@/service/console/browser', () => ({+ consoleBrowserLink: { call: mockRequest },}))vi.mock('@/service/workflow', () => ({@@ -178,8 +183,6 @@ const mockFetchCurrentValueOfConversationVariable = vi.mocked(fetchCurrentValueOfConversationVariable,)const mockCopy = vi.mocked(copy)-const mockFetchSuggestedQuestions = vi.mocked(fetchSuggestedQuestions)-const mockStopChatMessageResponding = vi.mocked(stopChatMessageResponding)const createConversationVariable = (overrides: Partial<ConversationVariable> = {},@@ -224,15 +227,9 @@ const createChatWrapperRef = () =>describe('debug-and-preview components', () => {beforeEach(() => {vi.clearAllMocks()- useAppStore.setState({- appDetail: {- id: 'app-1',- site: {- access_token: 'site-token',- app_base_url: 'https://example.com',- },- } as ReturnType<typeof useAppStore.getState>['appDetail'],- })+ routeParams.appId = 'app-1'+ mockRequest.mockReset()+ mockRequest.mockResolvedValue({ data: [] })mockUseChat.mockReturnValue(createChatState())mockFetchCurrentValueOfConversationVariable.mockResolvedValue(createConversationVariableResponse(),@@ -541,16 +538,13 @@ describe('debug-and-preview components', () => {)const sendCallbacks = handleSend.mock.calls[0]?.[1] as {- onGetSuggestedQuestions: (- messageId: string,- getAbortController: () => AbortController,- ) => void+ onGetSuggestedQuestions: (messageId: string, onCancel: (cancel: () => void) => void) => void}- sendCallbacks.onGetSuggestedQuestions('message-1', () => new AbortController())- expect(mockFetchSuggestedQuestions).toHaveBeenCalledWith(- 'app-1',- 'message-1',- expect.any(Function),+ await sendCallbacks.onGetSuggestedQuestions('message-1', () => {})+ expect(mockRequest).toHaveBeenCalledWith(+ ['apps', 'byAppId', 'chatMessages', 'byMessageId', 'suggestedQuestions', 'get'],+ { params: { app_id: 'app-1', message_id: 'message-1' } },+ expect.objectContaining({ signal: expect.any(AbortSignal) }),)await user.click(screen.getByRole('button', { name: 'regenerate-chat' }))@@ -572,16 +566,13 @@ describe('debug-and-preview components', () => {)const switchCallbacks = handleSwitchSibling.mock.calls[0]?.[1] as {- onGetSuggestedQuestions: (- messageId: string,- getAbortController: () => AbortController,- ) => void+ onGetSuggestedQuestions: (messageId: string, onCancel: (cancel: () => void) => void) => void}- switchCallbacks.onGetSuggestedQuestions('message-2', () => new AbortController())- expect(mockFetchSuggestedQuestions).toHaveBeenCalledWith(- 'app-1',- 'message-2',- expect.any(Function),+ await switchCallbacks.onGetSuggestedQuestions('message-2', () => {})+ expect(mockRequest).toHaveBeenCalledWith(+ ['apps', 'byAppId', 'chatMessages', 'byMessageId', 'suggestedQuestions', 'get'],+ { params: { app_id: 'app-1', message_id: 'message-2' } },+ expect.objectContaining({ signal: expect.any(AbortSignal) }),)await user.click(screen.getByRole('button', { name: 'submit-human-input' }))@@ -593,8 +584,12 @@ describe('debug-and-preview components', () => {})const stopResponding = mockUseChat.mock.calls[0]?.[3] as (taskId: string) => void- stopResponding('task-1')- expect(mockStopChatMessageResponding).toHaveBeenCalledWith('app-1', 'task-1')+ await stopResponding('task-1')+ expect(mockRequest).toHaveBeenCalledWith(+ ['apps', 'byAppId', 'chatMessages', 'byTaskId', 'stop', 'post'],+ { params: { app_id: 'app-1', task_id: 'task-1' } },+ expect.any(Object),+ )const subscription = mockUseSubscription.mock.calls[0]?.[0] as (payload: {type: stringdiff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.tsindex c6bb9811ad3..7974b447d6a 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-resume.spec.ts@@ -416,10 +416,12 @@ describe('useChat – handleResume', () => {})it('should fetch suggested questions when enabled', async () => {- const mockGetSuggested = vi.fn().mockImplementation((_id: string, getAbortCtrl: any) => {- getAbortCtrl(new AbortController())- return Promise.resolve({ data: ['s1'] })- })+ const mockGetSuggested = vi+ .fn()+ .mockImplementation((_id: string, onCancel: (cancel: () => void) => void) => {+ onCancel(vi.fn())+ return Promise.resolve({ data: ['s1'] })+ })let sendCallbacks: anymockHandleRun.mockImplementation((_params: any, callbacks: any) => {sendCallbacks = callbacksdiff --git a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.tsindex 8984593e15a..e5d5c58e010 100644--- a/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts+++ b/web/app/components/workflow/panel/debug-and-preview/__tests__/hooks/handle-stop-restart.spec.ts@@ -121,7 +121,7 @@ describe('useChat – handleStop', () => {expect(mockWfAbort).toHaveBeenCalledTimes(1)})- it('should abort suggestedQuestionsAbortController when set', async () => {+ it('should cancel the suggested questions request when stopped', async () => {const mockSqAbort = vi.fn()let capturedCb: any@@ -129,10 +129,12 @@ describe('useChat – handleStop', () => {capturedCb = callbacks})- const mockGetSuggested = vi.fn().mockImplementation((_id: string, getAbortCtrl: any) => {- getAbortCtrl({ abort: mockSqAbort } as any)- return Promise.resolve({ data: ['s'] })- })+ const mockGetSuggested = vi+ .fn()+ .mockImplementation((_id: string, onCancel: (cancel: () => void) => void) => {+ onCancel(mockSqAbort)+ return Promise.resolve({ data: ['s'] })+ })const { result } = renderHook(() =>useChat({ suggested_questions_after_answer: { enabled: true } }),diff --git a/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx b/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsxindex b6f6237c6e6..b1b785eabb8 100644--- a/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx+++ b/web/app/components/workflow/panel/debug-and-preview/chat-wrapper.tsx@@ -3,15 +3,16 @@ import type { ChatWrapperRefType } from './index'import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/answer/human-input-content/type'import type { ChatItem, OnSend } from '@/app/components/base/chat/types'import type { FileEntity } from '@/app/components/base/file-uploader/types'+import { useMutation, useQueryClient } from '@tanstack/react-query'import { memo, useCallback, useEffect, useImperativeHandle, useMemo } from 'react'import { useNodes } from 'reactflow'-import { useStore as useAppStore } from '@/app/components/app/store'import Chat from '@/app/components/base/chat/chat'import { getLastAnswer, isValidGeneratedAnswer } from '@/app/components/base/chat/utils'import { useFeatures } from '@/app/components/base/features/hooks'import { EVENT_WORKFLOW_STOP } from '@/app/components/workflow/variable-inspect/types'import { useEventEmitterContextContext } from '@/context/event-emitter'-import { fetchSuggestedQuestions, stopChatMessageResponding } from '@/service/debug'+import { useParams } from '@/next/navigation'+import { consoleQuery } from '@/service/console'import { useStore, useWorkflowStore } from '../../store'import { BlockEnum, WorkflowRunningStatus } from '../../types'import ConversationVariableModal from './conversation-variable-modal'@@ -38,7 +39,11 @@ const ChatWrapper = ({const nodes = useNodes<StartNodeType>()const startNode = nodes.find((node) => node.data.type === BlockEnum.Start)const startVariables = startNode?.data.variables- const appDetail = useAppStore((s) => s.appDetail)+ const { appId } = useParams<{ appId: string }>()+ const queryClient = useQueryClient()+ const { mutateAsync: stopChat } = useMutation(+ consoleQuery.apps.byAppId.chatMessages.byTaskId.stop.post.mutationOptions(),+ )const workflowStore = useWorkflowStore()const setMessageLogItem = useStore((state) => state.setMessageLogItem)const inputs = useStore((s) => s.inputs)@@ -79,6 +84,22 @@ const ChatWrapper = ({])const setShowFeaturesPanel = useStore((s) => s.setShowFeaturesPanel)+ const handleGetSuggestedQuestions = useCallback(+ (messageId: string, onCancel: (cancel: () => void) => void) => {+ const options =+ consoleQuery.apps.byAppId.chatMessages.byMessageId.suggestedQuestions.get.queryOptions({+ input: { params: { app_id: appId, message_id: messageId } },+ staleTime: 0,+ retry: false,+ })+ onCancel(() => {+ void queryClient.cancelQueries({ queryKey: options.queryKey, exact: true })+ })+ return queryClient.query(options)+ },+ [appId, queryClient],+ )+const {conversationId,chatList,@@ -97,7 +118,10 @@ const ChatWrapper = ({inputsForm: (startVariables || []) as any,},[],- (taskId) => stopChatMessageResponding(appDetail!.id, taskId),+ (taskId) =>+ stopChat({+ params: { app_id: appId, task_id: taskId },+ }),)const handleRestartChat = useCallback(() => {@@ -118,12 +142,11 @@ const ChatWrapper = ({(isRegenerate ? parentAnswer?.id : getLastAnswer(chatList)?.id) || undefined,},{- onGetSuggestedQuestions: (messageId, getAbortController) =>- fetchSuggestedQuestions(appDetail!.id, messageId, getAbortController),+ onGetSuggestedQuestions: handleGetSuggestedQuestions,},)},- [handleSend, workflowStore, conversationId, chatList, appDetail],+ [handleSend, workflowStore, conversationId, chatList, handleGetSuggestedQuestions],)const doRegenerate = useCallback(@@ -145,11 +168,10 @@ const ChatWrapper = ({const doSwitchSibling = useCallback((siblingMessageId: string) => {handleSwitchSibling(siblingMessageId, {- onGetSuggestedQuestions: (messageId, getAbortController) =>- fetchSuggestedQuestions(appDetail!.id, messageId, getAbortController),+ onGetSuggestedQuestions: handleGetSuggestedQuestions,})},- [handleSwitchSibling, appDetail],+ [handleSwitchSibling, handleGetSuggestedQuestions],)const doHumanInputFormSubmit = useCallback(@@ -200,7 +222,7 @@ const ChatWrapper = ({supportCitationHitInfo: true,} as any}- speechToTextTarget={appDetail ? { type: 'consoleApp', appId: appDetail.id } : undefined}+ speechToTextTarget={{ type: 'consoleApp', appId }}chatList={chatList}isResponding={isResponding}chatContainerClassName="px-3"diff --git a/web/app/components/workflow/panel/debug-and-preview/hooks.ts b/web/app/components/workflow/panel/debug-and-preview/hooks.tsindex 8949b2f56ed..5ad3a079673 100644--- a/web/app/components/workflow/panel/debug-and-preview/hooks.ts+++ b/web/app/components/workflow/panel/debug-and-preview/hooks.ts@@ -1,3 +1,4 @@+import type { SuggestedQuestionsResponse } from '@dify/contracts/api/console/apps/types.gen'import type { HumanInputFormSubmitData } from '@/app/components/base/chat/chat/answer/human-input-content/type'import type { InputForm } from '@/app/components/base/chat/chat/type'import type { ChatItem, ChatItemInTree, Inputs } from '@/app/components/base/chat/types'@@ -29,12 +30,11 @@ import { useWorkflowRun } from '../../hooks/use-workflow-run'import { useWorkflowStore } from '../../store'import { NodeRunningStatus, WorkflowRunningStatus } from '../../types'-type GetAbortController = (abortController: AbortController) => voidtype SendCallback = {onGetSuggestedQuestions?: (responseItemId: string,- getAbortController: GetAbortController,- ) => Promise<any>+ onCancel: (cancel: () => void) => void,+ ) => Promise<SuggestedQuestionsResponse>}export const useChat = (config: any,@@ -59,7 +59,7 @@ export const useChat = (const invalidAllLastRun = useInvalidAllLastRun(configsMap?.flowType, configsMap?.flowId)const { fetchInspectVars } = useSetWorkflowVarsWithValue()const [suggestedQuestions, setSuggestedQuestions] = useState<string[]>([])- const suggestedQuestionsAbortControllerRef = useRef<AbortController | null>(null)+ const cancelSuggestedQuestionsRef = useRef<(() => void) | null>(null)const { setIterTimes, setLoopTimes } = workflowStore.getState()const store = useStoreApi()@@ -185,8 +185,7 @@ export const useChat = (if (stopChat && taskIdRef.current) stopChat(taskIdRef.current)setIterTimes(DEFAULT_ITER_TIMES)setLoopTimes(DEFAULT_LOOP_TIMES)- if (suggestedQuestionsAbortControllerRef.current)- suggestedQuestionsAbortControllerRef.current.abort()+ cancelSuggestedQuestionsRef.current?.()if (workflowEventsAbortControllerRef.current) workflowEventsAbortControllerRef.current.abort()}, [handleResponding, setIterTimes, setLoopTimes, stopChat])@@ -394,10 +393,9 @@ export const useChat = (onGetSuggestedQuestions) {try {- const { data }: any = await onGetSuggestedQuestions(+ const { data } = await onGetSuggestedQuestions(responseItem.id,- (newAbortController) =>- (suggestedQuestionsAbortControllerRef.current = newAbortController),+ (cancel) => (cancelSuggestedQuestionsRef.current = cancel),)setSuggestedQuestions(data)} catch {@@ -779,10 +777,9 @@ export const useChat = (onGetSuggestedQuestions) {try {- const { data }: any = await onGetSuggestedQuestions(+ const { data } = await onGetSuggestedQuestions(messageId,- (newAbortController) =>- (suggestedQuestionsAbortControllerRef.current = newAbortController),+ (cancel) => (cancelSuggestedQuestionsRef.current = cancel),)setSuggestedQuestions(data)} catch {