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(web): preserve feedback state on submission failure (#40004)

yyh2dc6b080447f
diff --git a/web/app/components/base/chat/chat-with-history/context.ts b/web/app/components/base/chat/chat-with-history/context.ts
index 89496d39563..b6935e3db95 100644
--- a/web/app/components/base/chat/chat-with-history/context.ts
+++ b/web/app/components/base/chat/chat-with-history/context.ts
@@ -3,7 +3,7 @@
import type { RefObject } from 'react'
import type { ChatProps } from '../chat'
import type { Theme } from '../embedded-chatbot/theme/theme'
-import type { Callback, ChatConfig, ChatItemInTree, Feedback } from '../types'
+import type { Callback, ChatConfig, ChatItemInTree, OnFeedback } from '../types'
import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'
import { noop } from 'es-toolkit/function'
import { createContext, useContext } from 'use-context-selector'
@@ -35,7 +35,7 @@ export type ChatWithHistoryContextValue = {
isMobile: boolean
isInstalledApp: boolean
appId?: string
- handleFeedback: (messageId: string, feedback: Feedback) => void
+ handleFeedback: OnFeedback
currentChatInstanceRef: RefObject<{ handleStop: () => void }>
theme?: Theme
sidebarCollapseState?: boolean
@@ -76,7 +76,7 @@ export const ChatWithHistoryContext = createContext<ChatWithHistoryContextValue>
chatShouldReloadKey: '',
isMobile: false,
isInstalledApp: false,
- handleFeedback: noop,
+ handleFeedback: () => Promise.resolve(),
currentChatInstanceRef: { current: { handleStop: noop } },
sidebarCollapseState: false,
handleSidebarCollapse: noop,
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 e7d1ebc63c3..3fe556f0db2 100644
--- a/web/app/components/base/chat/chat-with-history/hooks.tsx
+++ b/web/app/components/base/chat/chat-with-history/hooks.tsx
@@ -1,6 +1,6 @@
import type { InstalledAppResponse } from '@dify/contracts/api/console/installed-apps/types.gen'
import type { ExtraContent } from '../chat/type'
-import type { Callback, ChatConfig, ChatItem, Feedback } from '../types'
+import type { Callback, ChatConfig, ChatItem, OnFeedback } from '../types'
import type { AppData, ConversationItem } from '@/models/share'
import type { HumanInputFilledFormData, HumanInputFormData } from '@/types/workflow'
import { toast } from '@langgenius/dify-ui/toast'
@@ -585,8 +585,8 @@ export const useChatWithHistory = (installedAppInfo?: InstalledAppResponse) => {
},
[handleConversationIdInfoChange, invalidateShareConversations],
)
- const handleFeedback = useCallback(
- async (messageId: string, feedback: Feedback) => {
+ const handleFeedback: OnFeedback = useCallback(
+ async (messageId, feedback) => {
await updateFeedback(
{
url: `/messages/${messageId}/feedbacks`,
diff --git a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
index a6ddf6f05d6..ef5d4158c76 100644
--- a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
@@ -725,6 +725,25 @@ describe('Operation', () => {
})
})
+ it('should keep the feedback dialog and local state unchanged when submission fails', async () => {
+ const user = userEvent.setup()
+ mockContextValue.onFeedback = vi.fn().mockRejectedValue(new Error('submission failed'))
+ renderOperation()
+
+ await user.click(
+ screen.getByRole('button', { name: 'table.header.adminRate: detail.operation.dislike' }),
+ )
+ const textarea = screen.getByRole('textbox', { name: 'feedback.content' })
+ await user.type(textarea, 'Needs work')
+ await user.click(screen.getByRole('button', { name: 'operation.submit' }))
+
+ expect(screen.getByRole('dialog', { name: 'feedback.title' })).toBeInTheDocument()
+ expect(textarea).toHaveValue('Needs work')
+ expect(
+ screen.queryByRole('button', { name: 'table.header.adminRate: operation.remove' }),
+ ).not.toBeInTheDocument()
+ })
+
it('should open feedback modal on admin dislike click', async () => {
const user = userEvent.setup()
renderOperation()
@@ -734,11 +753,49 @@ describe('Operation', () => {
expect(screen.getByRole('textbox'))!.toBeInTheDocument()
})
- it('should show user feedback read-only in admin bar when user has liked', () => {
- const item = { ...baseItem, feedback: { rating: 'like' as const } }
+ it('should expose user feedback as a non-interactive status in the admin bar', () => {
+ const item = {
+ ...baseItem,
+ feedback: { rating: 'dislike' as const, content: 'Needs work' },
+ }
renderOperation({ ...baseProps, item })
- const bar = screen.getByTestId('operation-bar')
- expect(bar.querySelectorAll('.i-ri-thumb-up-line').length).toBeGreaterThanOrEqual(2)
+
+ expect(
+ screen.getByRole('img', {
+ name: 'table.header.userRate: detail.operation.dislike - Needs work',
+ }),
+ ).toBeInTheDocument()
+ expect(
+ screen.queryByRole('button', {
+ name: 'table.header.userRate: detail.operation.dislike',
+ }),
+ ).not.toBeInTheDocument()
+ })
+
+ it('should reflect feedback received from refreshed message props', () => {
+ const { rerender } = renderOperation()
+
+ rerender(
+ <div className="group">
+ <Operation
+ {...baseProps}
+ item={{
+ ...baseItem,
+ feedback: { rating: 'like' },
+ adminFeedback: { rating: 'dislike', content: 'Needs work' },
+ }}
+ />
+ </div>,
+ )
+
+ expect(
+ screen.getByRole('img', {
+ name: 'table.header.userRate: detail.operation.like',
+ }),
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('button', { name: 'table.header.adminRate: operation.remove' }),
+ ).toBeInTheDocument()
})
it('should show separator in admin bar when user has feedback', () => {
diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsx
index 09be259d7e1..8298b66d310 100644
--- a/web/app/components/base/chat/chat/answer/operation.tsx
+++ b/web/app/components/base/chat/chat/answer/operation.tsx
@@ -98,20 +98,19 @@ function Operation({
const [feedbackContent, setFeedbackContent] = useState('')
const { id, isOpeningStatement, annotation, feedback, adminFeedback, humanInputFormDataList } =
item
- const [userLocalFeedback, setUserLocalFeedback] = useState(feedback)
- const [adminLocalFeedback, setAdminLocalFeedback] = useState(adminFeedback)
+ const [userFeedbackOverride, setUserFeedbackOverride] = useState<Feedback>()
+ const [adminFeedbackOverride, setAdminFeedbackOverride] = useState<Feedback>()
const [feedbackTarget, setFeedbackTarget] = useState<'user' | 'admin'>('user')
const feedbackTextareaId = useId()
- const userFeedback = feedback
-
const content = getPublicResponseContent(item)
const hasPublicContent = !!content.trim()
- const displayUserFeedback = userLocalFeedback ?? userFeedback
+ const displayUserFeedback = userFeedbackOverride ?? feedback
+ const displayAdminFeedback = adminFeedbackOverride ?? adminFeedback
const hasUserFeedback = !!displayUserFeedback?.rating
- const hasAdminFeedback = !!adminLocalFeedback?.rating
+ const hasAdminFeedback = !!displayAdminFeedback?.rating
const shouldShowUserFeedbackBar =
!isOpeningStatement && config?.supportFeedback && !!onFeedback && !config?.supportAnnotation
@@ -155,18 +154,23 @@ function Operation({
content?: string,
target: 'user' | 'admin' = 'user',
) => {
- if (!config?.supportFeedback || !onFeedback) return
+ if (!config?.supportFeedback || !onFeedback) return false
- await onFeedback?.(id, { rating, content })
+ try {
+ await onFeedback(id, { rating, content })
- const nextFeedback = rating === null ? { rating: null } : { rating, content }
+ const nextFeedback = rating === null ? { rating: null } : { rating, content }
- if (target === 'admin') setAdminLocalFeedback(nextFeedback)
- else setUserLocalFeedback(nextFeedback)
+ if (target === 'admin') setAdminFeedbackOverride(nextFeedback)
+ else setUserFeedbackOverride(nextFeedback)
+ return true
+ } catch {
+ return false
+ }
}
const handleLikeClick = (target: 'user' | 'admin') => {
- handleFeedback('like', undefined, target)
+ void handleFeedback('like', undefined, target)
}
const handleDislikeClick = (target: 'user' | 'admin') => {
@@ -175,7 +179,9 @@ function Operation({
}
const handleFeedbackSubmit = async () => {
- await handleFeedback('dislike', feedbackContent, feedbackTarget)
+ const succeeded = await handleFeedback('dislike', feedbackContent, feedbackTarget)
+ if (!succeeded) return
+
setFeedbackContent('')
setIsShowFeedbackModal(false)
}
@@ -291,21 +297,26 @@ function Operation({
<FeedbackTooltip
content={buildFeedbackTooltip(displayUserFeedback, userFeedbackLabel)}
>
- {displayUserFeedback.rating === 'like' ? (
- <ActionButton
- aria-label={`${userFeedbackLabel}: ${likeLabel}`}
- state={ActionButtonState.Active}
- >
- <span aria-hidden="true" className="i-ri-thumb-up-line size-4" />
- </ActionButton>
- ) : (
- <ActionButton
- aria-label={`${userFeedbackLabel}: ${dislikeLabel}`}
- state={ActionButtonState.Destructive}
- >
- <span aria-hidden="true" className="i-ri-thumb-down-line size-4" />
- </ActionButton>
- )}
+ <span
+ role="img"
+ aria-label={buildFeedbackTooltip(displayUserFeedback, userFeedbackLabel)}
+ className={cn(
+ 'inline-flex size-6 items-center justify-center rounded-lg p-0.5',
+ displayUserFeedback.rating === 'like'
+ ? 'bg-state-accent-active text-text-accent'
+ : 'bg-state-destructive-hover text-text-destructive',
+ )}
+ >
+ <span
+ aria-hidden="true"
+ className={cn(
+ 'size-4',
+ displayUserFeedback.rating === 'like'
+ ? 'i-ri-thumb-up-line'
+ : 'i-ri-thumb-down-line',
+ )}
+ />
+ </span>
</FeedbackTooltip>
)}
@@ -314,18 +325,18 @@ function Operation({
)}
{hasAdminFeedback ? (
<FeedbackTooltip
- content={buildFeedbackTooltip(adminLocalFeedback, adminFeedbackLabel)}
+ content={buildFeedbackTooltip(displayAdminFeedback, adminFeedbackLabel)}
>
<ActionButton
aria-label={`${adminFeedbackLabel}: ${removeFeedbackLabel}`}
state={
- adminLocalFeedback?.rating === 'like'
+ displayAdminFeedback?.rating === 'like'
? ActionButtonState.Active
: ActionButtonState.Destructive
}
onClick={() => handleFeedback(null, undefined, 'admin')}
>
- {adminLocalFeedback?.rating === 'like' ? (
+ {displayAdminFeedback?.rating === 'like' ? (
<span aria-hidden="true" className="i-ri-thumb-up-line size-4" />
) : (
<span aria-hidden="true" className="i-ri-thumb-down-line size-4" />
@@ -335,12 +346,12 @@ function Operation({
) : (
<>
<FeedbackTooltip
- content={buildFeedbackTooltip(adminLocalFeedback, adminFeedbackLabel)}
+ content={buildFeedbackTooltip(displayAdminFeedback, adminFeedbackLabel)}
>
<ActionButton
aria-label={`${adminFeedbackLabel}: ${likeLabel}`}
state={
- adminLocalFeedback?.rating === 'like'
+ displayAdminFeedback?.rating === 'like'
? ActionButtonState.Active
: ActionButtonState.Default
}
@@ -350,12 +361,12 @@ function Operation({
</ActionButton>
</FeedbackTooltip>
<FeedbackTooltip
- content={buildFeedbackTooltip(adminLocalFeedback, adminFeedbackLabel)}
+ content={buildFeedbackTooltip(displayAdminFeedback, adminFeedbackLabel)}
>
<ActionButton
aria-label={`${adminFeedbackLabel}: ${dislikeLabel}`}
state={
- adminLocalFeedback?.rating === 'dislike'
+ displayAdminFeedback?.rating === 'dislike'
? ActionButtonState.Destructive
: ActionButtonState.Default
}
diff --git a/web/app/components/base/chat/chat/index.tsx b/web/app/components/base/chat/chat/index.tsx
index c0ef9fc07c3..c19090fcd64 100644
--- a/web/app/components/base/chat/chat/index.tsx
+++ b/web/app/components/base/chat/chat/index.tsx
@@ -1,6 +1,6 @@
import type { FC, ReactNode } from 'react'
import type { Theme } from '../embedded-chatbot/theme/theme'
-import type { ChatConfig, ChatItem, Feedback, OnRegenerate, OnSend } from '../types'
+import type { ChatConfig, ChatItem, OnFeedback, OnRegenerate, OnSend } from '../types'
import type { HumanInputFormSubmitData } from './answer/human-input-content/type'
import type { AnswerActionPosition } from './answer/operation'
import type { InputForm } from './type'
@@ -58,7 +58,7 @@ export type ChatProps = {
onAnnotationRemoved?: (index: number) => void
chatNode?: ReactNode
disableFeedback?: boolean
- onFeedback?: (messageId: string, feedback: Feedback) => void
+ onFeedback?: OnFeedback
chatAnswerContainerInner?: string
hideProcessDetail?: boolean
hideLogModal?: boolean
diff --git a/web/app/components/base/chat/embedded-chatbot/context.ts b/web/app/components/base/chat/embedded-chatbot/context.ts
index 658802eb533..64c91694c36 100644
--- a/web/app/components/base/chat/embedded-chatbot/context.ts
+++ b/web/app/components/base/chat/embedded-chatbot/context.ts
@@ -1,7 +1,7 @@
'use client'
import type { RefObject } from 'react'
-import type { ChatConfig, ChatItem, Feedback } from '../types'
+import type { ChatConfig, ChatItem, OnFeedback } from '../types'
import type { Theme } from './theme/theme'
import type { AppConversationData, AppData, AppMeta, ConversationItem } from '@/models/share'
import { noop } from 'es-toolkit/function'
@@ -33,7 +33,7 @@ export type EmbeddedChatbotContextValue = {
allowResetChat: boolean
appId?: string
disableFeedback?: boolean
- handleFeedback: (messageId: string, feedback: Feedback) => void
+ handleFeedback: OnFeedback
currentChatInstanceRef: RefObject<{ handleStop: () => void }>
theme?: Theme
clearChatList?: boolean
@@ -71,7 +71,7 @@ export const EmbeddedChatbotContext = createContext<EmbeddedChatbotContextValue>
appSourceType: AppSourceType.webApp,
isInstalledApp: false,
allowResetChat: true,
- handleFeedback: noop,
+ handleFeedback: () => Promise.resolve(),
currentChatInstanceRef: { current: { handleStop: noop } },
clearChatList: false,
setClearChatList: noop,
diff --git a/web/app/components/base/chat/embedded-chatbot/hooks.tsx b/web/app/components/base/chat/embedded-chatbot/hooks.tsx
index e66c7551a31..991c4760a89 100644
--- a/web/app/components/base/chat/embedded-chatbot/hooks.tsx
+++ b/web/app/components/base/chat/embedded-chatbot/hooks.tsx
@@ -1,4 +1,4 @@
-import type { ChatConfig, ChatItem, Feedback } from '../types'
+import type { ChatConfig, ChatItem, OnFeedback } from '../types'
/* oxlint-disable typescript/no-explicit-any */
import type { InputValueTypes } from '@/app/components/share/text-generation/types'
import type { Locale } from '@/i18n-config'
@@ -434,8 +434,8 @@ export const useEmbeddedChatbot = (appSourceType: AppSourceType, tryAppId?: stri
},
[handleConversationIdInfoChange, invalidateShareConversations],
)
- const handleFeedback = useCallback(
- async (messageId: string, feedback: Feedback) => {
+ const handleFeedback: OnFeedback = useCallback(
+ async (messageId, feedback) => {
await updateFeedback(
{
url: `/messages/${messageId}/feedbacks`,
diff --git a/web/app/components/base/chat/types.ts b/web/app/components/base/chat/types.ts
index cad33bddbfe..be36cd96a63 100644
--- a/web/app/components/base/chat/types.ts
+++ b/web/app/components/base/chat/types.ts
@@ -75,3 +75,5 @@ export type Feedback = {
rating: 'like' | 'dislike' | null
content?: string | null
}
+
+export type OnFeedback = (messageId: string, feedback: Feedback) => Promise<void>
diff --git a/web/features/agent-v2/agent-detail/logs/__tests__/log-detail-panel.spec.tsx b/web/features/agent-v2/agent-detail/logs/__tests__/log-detail-panel.spec.tsx
index 970c70e68f7..f968c1277a1 100644
--- a/web/features/agent-v2/agent-detail/logs/__tests__/log-detail-panel.spec.tsx
+++ b/web/features/agent-v2/agent-detail/logs/__tests__/log-detail-panel.spec.tsx
@@ -2,7 +2,8 @@ import type {
AgentLogConversationItemResponse,
AgentLogMessageListResponse,
} from '@dify/contracts/api/console/agent/types.gen'
-import type { FeedbackFunc, IChatItem } from '@/app/components/base/chat/chat/type'
+import type { IChatItem } from '@/app/components/base/chat/chat/type'
+import type { OnFeedback } from '@/app/components/base/chat/types'
import { QueryClient } from '@tanstack/react-query'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
@@ -25,11 +26,13 @@ vi.mock('@/app/components/base/chat/chat', () => ({
}: {
chatList: IChatItem[]
config?: { supportFeedback?: boolean }
- onFeedback?: FeedbackFunc
+ onFeedback?: OnFeedback
}) => {
mocks.chatProps({ chatList, config, onFeedback })
return (
- <button onClick={() => void onFeedback?.('message-1', { rating: 'like' })}>
+ <button
+ onClick={() => void onFeedback?.('message-1', { rating: 'like' }).catch(() => undefined)}
+ >
submit-feedback
</button>
)
diff --git a/web/features/agent-v2/agent-detail/logs/components/log-detail-panel.tsx b/web/features/agent-v2/agent-detail/logs/components/log-detail-panel.tsx
index fdead6c73d9..098bda318c1 100644
--- a/web/features/agent-v2/agent-detail/logs/components/log-detail-panel.tsx
+++ b/web/features/agent-v2/agent-detail/logs/components/log-detail-panel.tsx
@@ -2,8 +2,8 @@ import type {
AgentLogConversationItemResponse,
AgentLogMessageItemResponse,
} from '@dify/contracts/api/console/agent/types.gen'
-import type { FeedbackType, IChatItem } from '@/app/components/base/chat/chat/type'
-import type { ChatConfig } from '@/app/components/base/chat/types'
+import type { IChatItem } from '@/app/components/base/chat/chat/type'
+import type { ChatConfig, OnFeedback } from '@/app/components/base/chat/types'
import { toast } from '@langgenius/dify-ui/toast'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
@@ -61,7 +61,7 @@ export function AgentLogDetailPanel({
messages: messagesQuery.data?.data ?? [],
})
: []
- const handleFeedback = async (messageId: string, feedback: FeedbackType) => {
+ const handleFeedback: OnFeedback = async (messageId, feedback) => {
try {
await feedbackMutation.mutateAsync({
params: { agent_id: agentId },
@@ -80,10 +80,9 @@ export function AgentLogDetailPanel({
}),
])
toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
- return true
- } catch {
+ } catch (error) {
toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
- return false
+ throw error
}
}