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
fix(web): preserve chat feedback drafts until submission succeeds (#43520)
yyh2108cac1d029
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex f3e076f6cc4..636761089af 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -761,7 +761,7 @@},"web/app/components/base/chat/chat/type.ts": {"typescript/no-explicit-any": {- "count": 5+ "count": 4}},"web/app/components/base/chat/chat/utils.ts": {diff --git a/web/app/components/app/log/__tests__/list.spec.tsx b/web/app/components/app/log/__tests__/list.spec.tsxindex 6da26aadd64..58fa91eb8ef 100644--- a/web/app/components/app/log/__tests__/list.spec.tsx+++ b/web/app/components/app/log/__tests__/list.spec.tsx@@ -13,6 +13,7 @@ import ConversationList from '../list'const mockFetchChatMessages = vi.fn()const mockUpdateLogMessageFeedbacks = vi.fn()+const mockFeedbackResult = vi.fn()const mockUpdateLogMessageAnnotations = vi.fn()const mockOnRefresh = vi.fn()const mockCompletionRefetch = vi.fn()@@ -82,11 +83,11 @@ vi.mock('@/app/components/app/text-generate/item', () => ({}: {content: stringonOpenLog?: (item: IChatItem) => void- onFeedback: (value: { rating: string; content?: string }) => Promise<boolean>+ onFeedback: (value: { rating: string; content?: string }) => void}) => (<div data-testid="text-generation" data-log-enabled={String(!!onOpenLog)}><div>{content}</div>- <button onClick={() => void onFeedback({ rating: 'like', content: 'great' })}>+ <button onClick={() => onFeedback({ rating: 'like', content: 'great' })}>completion-feedback</button></div>@@ -104,7 +105,7 @@ vi.mock('@/app/components/base/chat/chat', () => ({onOpenLog,}: {chatList: Array<{ id: string }>- onFeedback: (mid: string, value: { rating: string; content?: string }) => Promise<boolean>+ onFeedback: (mid: string, value: { rating: string; content?: string }) => Promise<void>onAnnotationAdded: (annotationId: string,authorName: string,@@ -187,7 +188,14 @@ vi.mock('@/app/components/base/chat/chat', () => ({</button></>)}- <button onClick={() => void onFeedback('message-1', { rating: 'like', content: 'nice' })}>+ <button+ onClick={() => {+ void onFeedback('message-1', { rating: 'like', content: 'nice' }).then(+ () => mockFeedbackResult(true),+ () => mockFeedbackResult(false),+ )+ }}+ >chat-feedback</button><button@@ -426,81 +434,88 @@ describe('ConversationList', () => {expect(update.options.history).toBe('replace')})- it('should render chat conversation details and submit feedback from the chat panel', async () => {- mockChatConversationDetail = {- id: 'conversation-1',- created_at: 1710000000,- model_config: {- model: 'gpt-4o',- configs: {- introduction: 'Hello there',- },- user_input_form: [- {- query: {- variable: 'query',- },+ it.each([true, false])(+ 'settles admin feedback with the request outcome (success: %s)',+ async (succeeded) => {+ mockFeedbackResult.mockClear()+ if (!succeeded)+ mockUpdateLogMessageFeedbacks.mockRejectedValueOnce(new Error('Feedback failed'))+ mockChatConversationDetail = {+ id: 'conversation-1',+ created_at: 1710000000,+ model_config: {+ model: 'gpt-4o',+ configs: {+ introduction: 'Hello there',},- ],- },- message: {- inputs: {- query: 'Latest question',+ user_input_form: [+ {+ query: {+ variable: 'query',+ },+ },+ ],},- },- }- mockFetchChatMessages.mockResolvedValue({- data: [- {- id: 'message-1',- answer: 'Assistant reply',- query: 'Latest question',- created_at: 1710000000,+ message: {inputs: {query: 'Latest question',},- feedbacks: [],- message: [],- message_files: [],},- ],- has_more: false,- })+ }+ mockFetchChatMessages.mockResolvedValue({+ data: [+ {+ id: 'message-1',+ answer: 'Assistant reply',+ query: 'Latest question',+ created_at: 1710000000,+ inputs: {+ query: 'Latest question',+ },+ feedbacks: [],+ message: [],+ message_files: [],+ },+ ],+ has_more: false,+ })- renderConversationList({- searchParams: '?page=2&conversation_id=conversation-1',- })+ renderConversationList({+ searchParams: '?page=2&conversation_id=conversation-1',+ })- await waitFor(() => {- expect(mockFetchChatMessages).toHaveBeenCalledWith({- url: '/apps/app-1/chat-messages',- params: {- conversation_id: 'conversation-1',- limit: 10,- },+ await waitFor(() => {+ expect(mockFetchChatMessages).toHaveBeenCalledWith({+ url: '/apps/app-1/chat-messages',+ params: {+ conversation_id: 'conversation-1',+ limit: 10,+ },+ })})- })- await waitFor(() => {- expect(screen.getByTestId('chat-panel')).toBeInTheDocument()- })+ await waitFor(() => {+ expect(screen.getByTestId('chat-panel')).toBeInTheDocument()+ })- expect(screen.getByTestId('var-panel')).toHaveTextContent('query:Latest question')- expect(screen.getByTestId('model-info')).toHaveTextContent('gpt-4o')+ expect(screen.getByTestId('var-panel')).toHaveTextContent('query:Latest question')+ expect(screen.getByTestId('model-info')).toHaveTextContent('gpt-4o')- fireEvent.click(screen.getByText('chat-feedback'))+ fireEvent.click(screen.getByText('chat-feedback'))- await waitFor(() => {- expect(mockUpdateLogMessageFeedbacks).toHaveBeenCalledWith({- url: '/apps/app-1/feedbacks',- body: {- message_id: 'message-1',- rating: 'like',- content: 'nice',- },+ await waitFor(() => {+ expect(mockUpdateLogMessageFeedbacks).toHaveBeenCalledWith({+ url: '/apps/app-1/feedbacks',+ body: {+ message_id: 'message-1',+ rating: 'like',+ content: 'nice',+ },+ })})- })- })+ await waitFor(() => expect(mockFeedbackResult).toHaveBeenCalledWith(succeeded))+ },+ )it.each([['chatbot', AppModeEnum.CHAT, 'false'],diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsxindex 536a31fadb9..7cc8b07c7b1 100644--- a/web/app/components/app/log/list.tsx+++ b/web/app/components/app/log/list.tsx@@ -499,7 +499,9 @@ function DetailPanel({ appDetail, detail, onClose, onFeedback }: IDetailPanel) {onRetry={noop}supportFeedbackfeedback={detail.message.feedbacks.find((item: any) => item.from_source === 'admin')}- onFeedback={(feedback) => onFeedback(detail.message.id, feedback)}+ onFeedback={(feedback) => {+ onFeedback(detail.message.id, feedback).catch(noop)+ }}isShowTextToSpeechsiteInfo={null}/>@@ -634,22 +636,13 @@ const CompletionConversationDetailComp: FC<ConversationDetailProps> = ({useCompletionConversationDetail(appDetail.id, conversationId)const { t } = useTranslation(['appLog', 'common'])- const handleFeedback = async (- mid: string,- { rating, content }: FeedbackType,- ): Promise<boolean> => {- try {- await updateLogMessageFeedbacks({- url: `/apps/${appDetail.id}/feedbacks`,- body: { message_id: mid, rating, content: content ?? undefined },- })- conversationDetailMutate()- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))- return true- } catch {- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))- return false- }+ const handleFeedback = async (mid: string, { rating, content }: FeedbackType) => {+ await updateLogMessageFeedbacks({+ url: `/apps/${appDetail.id}/feedbacks`,+ body: { message_id: mid, rating, content: content ?? undefined },+ })+ conversationDetailMutate()+ toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))}const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {@@ -698,21 +691,12 @@ const ChatConversationDetailComp: FC<ConversationDetailProps> = ({const { data: conversationDetail } = useChatConversationDetail(appDetail.id, conversationId)const { t } = useTranslation(['appLog', 'common'])- const handleFeedback = async (- mid: string,- { rating, content }: FeedbackType,- ): Promise<boolean> => {- try {- await updateLogMessageFeedbacks({- url: `/apps/${appDetail.id}/feedbacks`,- body: { message_id: mid, rating, content: content ?? undefined },- })- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))- return true- } catch {- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))- return false- }+ const handleFeedback = async (mid: string, { rating, content }: FeedbackType) => {+ await updateLogMessageFeedbacks({+ url: `/apps/${appDetail.id}/feedbacks`,+ body: { message_id: mid, rating, content: content ?? undefined },+ })+ toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))}const handleAnnotation = async (mid: string, value: string): Promise<boolean> => {diff --git a/web/app/components/base/chat/chat/answer/__tests__/feedback-focus.browser.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/feedback-focus.browser.spec.tsxindex de2b015d8db..a441a238487 100644--- a/web/app/components/base/chat/chat/answer/__tests__/feedback-focus.browser.spec.tsx+++ b/web/app/components/base/chat/chat/answer/__tests__/feedback-focus.browser.spec.tsx@@ -1,16 +1,11 @@import type { ChatItem } from '../../../types'import { userEvent } from 'vite-plus/test/browser'import { render } from 'vitest-browser-react'+import { PromptMode } from '@/models/debug'+import { ChatContextProvider } from '../../context-provider'import Operation from '../operation'-const feedback = vi.hoisted(() => ({ admin: false, onFeedback: vi.fn() }))--vi.mock('../../context', () => ({- useChatContext: () => ({- config: { supportFeedback: true, supportAnnotation: feedback.admin },- onFeedback: feedback.onFeedback,- }),-}))+const feedback = vi.hoisted(() => ({ onFeedback: vi.fn() }))// These independently owned features do not participate in feedback focus restoration.vi.mock('@/app/components/app/annotation/edit-annotation-modal', () => ({ default: () => null }))@@ -23,6 +18,51 @@ vi.mock('@/app/components/base/chat/chat/log', () => ({ default: () => null }))const item: ChatItem = { id: 'answer', content: 'An answer', isAnswer: true }+function FeedbackAnswer({ admin = false }: { admin?: boolean }) {+ return (+ <ChatContextProvider+ chatList={[item]}+ config={{+ opening_statement: '',+ pre_prompt: '',+ prompt_type: PromptMode.simple,+ user_input_form: [],+ more_like_this: { enabled: false },+ suggested_questions_after_answer: { enabled: false },+ speech_to_text: { enabled: false },+ text_to_speech: { enabled: false },+ retriever_resource: { enabled: false },+ sensitive_word_avoidance: { enabled: false },+ agent_mode: { enabled: false, tools: [] },+ dataset_configs: {+ retrieval_model: 'single',+ reranking_model: { reranking_provider_name: '', reranking_model_name: '' },+ top_k: 4,+ score_threshold_enabled: false,+ score_threshold: null,+ datasets: { datasets: [] },+ },+ supportFeedback: true,+ supportAnnotation: admin,+ }}+ onFeedback={feedback.onFeedback}+ >+ <button type="button">Before answer</button>+ <article aria-label="Answer" className="group relative m-10 h-32 w-96">+ <p>{item.content}</p>+ <Operation+ item={item}+ question="Question"+ index={0}+ maxSize={500}+ contentWidth={100}+ hasWorkflowProcess={false}+ />+ </article>+ </ChatContextProvider>+ )+}+// The exit transition is rendered by Chromium; the default test setup disables it.it.each(['cancel', 'submit'])('preserves the feedback draft during the %s exit animation',@@ -30,22 +70,9 @@ it.each(['cancel', 'submit'])(const settings = globalThis as typeof globalThis & { BASE_UI_ANIMATIONS_DISABLED: boolean }const animationsDisabled = settings.BASE_UI_ANIMATIONS_DISABLEDsettings.BASE_UI_ANIMATIONS_DISABLED = false- feedback.admin = falsefeedback.onFeedback.mockReset().mockResolvedValue(undefined)try {- const screen = await render(- <article aria-label="Answer" className="group relative m-10 h-32 w-96">- <p>{item.content}</p>- <Operation- item={item}- question="Question"- index={0}- maxSize={500}- contentWidth={100}- hasWorkflowProcess={false}- />- </article>,- )+ const screen = await render(<FeedbackAnswer />)await screen.getByRole('article', { name: 'Answer' }).hover()const trigger = screen.getByRole('button', {name: 'appLog.table.header.userRate: appLog.detail.operation.dislike',@@ -100,23 +127,7 @@ describe('Feedback dialog focus', () => {])('returns to the visible feedback button after $close (admin: $admin)',async ({ admin, close }) => {- feedback.admin = admin- const screen = await render(- <>- <button type="button">Before answer</button>- <article aria-label="Answer" className="group relative m-10 h-32 w-96">- <p>{item.content}</p>- <Operation- item={item}- question="Question"- index={0}- maxSize={500}- contentWidth={100}- hasWorkflowProcess={false}- />- </article>- </>,- )+ const screen = await render(<FeedbackAnswer admin={admin} />)const trigger = screen.getByRole('button', {name: `${admin ? 'appLog.table.header.adminRate' : 'appLog.table.header.userRate'}: appLog.detail.operation.dislike`,})@@ -151,3 +162,71 @@ describe('Feedback dialog focus', () => {},)})++it('keeps the pending feedback focused and retries the draft after a failure', async () => {+ let rejectFeedback!: (reason: Error) => void+ feedback.onFeedback+ .mockReset()+ .mockReturnValueOnce(+ new Promise<void>((_resolve, reject) => {+ rejectFeedback = reject+ }),+ )+ .mockResolvedValue(undefined)+ const screen = await render(<FeedbackAnswer />)+ await screen.getByRole('article', { name: 'Answer' }).hover()+ const trigger = screen.getByRole('button', {+ name: 'appLog.table.header.userRate: appLog.detail.operation.dislike',+ })+ await trigger.click()+ const dialog = screen.getByRole('dialog', { name: 'common.feedback.title' })+ const textbox = dialog.getByRole('textbox', { name: 'common.feedback.content' })+ await textbox.fill('Please explain')+ await userEvent.keyboard('{End}{Enter}the answer')+ const draft = 'Please explain\nthe answer'+ await expect.element(textbox).toHaveValue(draft)+ expect(feedback.onFeedback).not.toHaveBeenCalled()++ const submit = dialog.getByRole('button', { name: 'common.operation.submit' })+ await submit.click()+ await expect.element(submit).toHaveFocus()+ await expect.element(submit).toHaveAttribute('aria-disabled', 'true')+ await expect.element(textbox).toHaveAttribute('readonly')+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.close' }))+ .toBeDisabled()+ await expect+ .element(dialog.getByRole('button', { name: 'common.operation.cancel' }))+ .toBeDisabled()+ await userEvent.keyboard('{Enter}{Enter}{Escape}')+ await expect.element(dialog).toBeVisible()+ expect(feedback.onFeedback).toHaveBeenCalledTimes(1)+ expect(feedback.onFeedback).toHaveBeenCalledWith('answer', {+ rating: 'dislike',+ content: draft,+ })++ const outside = document.elementFromPoint(4, 4)!+ await userEvent.click(outside, { position: { x: 4, y: 4 } })+ await expect.element(dialog).toBeVisible()+ await userEvent.tab()+ await expect.poll(() => dialog.element().contains(document.activeElement)).toBe(true)+ await textbox.click()+ await userEvent.keyboard('ignored')+ await expect.element(textbox).toHaveValue(draft)++ rejectFeedback(new Error('Feedback request failed'))+ await expect.element(textbox).not.toHaveAttribute('readonly')+ await expect.element(submit).not.toHaveAttribute('aria-disabled', 'true')+ await expect.element(dialog).toBeVisible()+ await expect.element(textbox).toHaveValue(draft)+ await submit.click()+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ await expect.element(trigger).toHaveAttribute('aria-pressed', 'true')+ expect(feedback.onFeedback).toHaveBeenCalledTimes(2)+ expect(feedback.onFeedback).toHaveBeenLastCalledWith('answer', {+ rating: 'dislike',+ content: draft,+ })+})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.tsxindex e5848ef6f36..786775c1b72 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@@ -1,8 +1,9 @@import type { ChatConfig, ChatItem } from '../../../types'import type { ChatContextValue } from '../../context'-import { render, screen } from '@testing-library/react'+import { act, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import copy from 'copy-to-clipboard'+import { ChatContextProvider } from '../../context-provider'import Operation from '../operation'const { mockSetShowAnnotationFullModal, mockT, mockAddAnnotation } = vi.hoisted(() => {@@ -151,10 +152,6 @@ const mockContextValue: ChatContextValue = {readonly: false,}-vi.mock('../../context', () => ({- useChatContext: () => mockContextValue,-}))-vi.mock('react-i18next', async () => {const { withSelectorKey } = await import('@/test/i18n-mock')return {@@ -219,6 +216,11 @@ describe('Operation', () => {<div className="group"><Operation {...props} /></div>,+ {+ wrapper: ({ children }) => (+ <ChatContextProvider {...mockContextValue}>{children}</ChatContextProvider>+ ),+ },)}@@ -237,6 +239,70 @@ describe('Operation', () => {mockAddAnnotation.mockResolvedValue({ id: 'ann-new', account: { name: 'Test User' } })})+ describe('feedback submission sessions', () => {+ it.each([{ admin: false }, { admin: true }])(+ 'preserves the draft after a failed submission and retries successfully (admin: $admin)',+ async ({ admin }) => {+ mockContextValue.config = makeChatConfig({+ supportFeedback: true,+ supportAnnotation: admin,+ })+ const onFeedback = vi.fn<NonNullable<ChatContextValue['onFeedback']>>()+ onFeedback.mockRejectedValueOnce(new Error('Feedback failed')).mockResolvedValueOnce()+ mockContextValue.onFeedback = onFeedback+ const user = userEvent.setup()+ renderOperation()+ const name = `${admin ? 'table.header.adminRate' : 'table.header.userRate'}: detail.operation.dislike`+ await user.click(screen.getByRole('button', { name }))+ const input = screen.getByRole('textbox', { name: 'feedback.content' })+ await user.type(input, 'Needs more detail')+ await user.click(screen.getByRole('button', { name: 'operation.submit' }))+ await waitFor(() => expect(input).not.toHaveAttribute('readonly'))+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(input).toHaveValue('Needs more detail')+ await user.type(input, ' please')+ await user.click(screen.getByRole('button', { name: 'operation.submit' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(onFeedback).toHaveBeenLastCalledWith('msg-1', {+ rating: 'dislike',+ content: 'Needs more detail please',+ })+ expect(screen.getByRole('button', { name })).toHaveAttribute('aria-pressed', 'true')+ },+ )++ it('keeps one pending submission open and prevents edits or duplicate submissions', async () => {+ let resolve!: () => void+ const pending = new Promise<void>((done) => {+ resolve = done+ })+ const onFeedback = vi.fn().mockReturnValue(pending)+ mockContextValue.onFeedback = onFeedback+ const user = userEvent.setup()+ renderOperation()+ await user.click(+ screen.getByRole('button', { name: 'table.header.userRate: detail.operation.dislike' }),+ )+ const input = screen.getByRole('textbox', { name: 'feedback.content' })+ await user.type(input, 'Original draft')+ const submit = screen.getByRole('button', { name: 'operation.submit' })+ await user.click(submit)+ expect(submit).toHaveAttribute('aria-disabled', 'true')+ expect(input).toHaveAttribute('readonly')+ await user.keyboard('{Escape}')+ await user.click(screen.getByRole('button', { name: 'operation.cancel' }))+ await user.click(screen.getByRole('button', { name: 'operation.close' }))+ await user.click(submit)+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(onFeedback).toHaveBeenCalledTimes(1)+ await act(async () => {+ resolve()+ await pending+ })+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ })+ })+describe('Rendering', () => {it('should hide action buttons for opening statements', () => {const item = { ...baseItem, isOpeningStatement: true }diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsxindex 8a3a3f76f9a..e6cbbaaca0d 100644--- a/web/app/components/base/chat/chat/answer/operation.tsx+++ b/web/app/components/base/chat/chat/answer/operation.tsx@@ -1,3 +1,4 @@+import type { DialogActions } from '@langgenius/dify-ui/dialog'import type { ReactElement, ReactNode } from 'react'import type { ChatItem, Feedback } from '../../types'import { Button } from '@langgenius/dify-ui/button'@@ -78,6 +79,75 @@ const FeedbackTooltip = ({ content, children }: FeedbackTooltipProps) => {)}+type FeedbackFormProps = {+ isSubmitting: boolean+ onSubmit: (content: string) => void+}++function FeedbackForm({ isSubmitting, onSubmit }: FeedbackFormProps) {+ const { t } = useTranslation(['common'])+ const feedbackTextareaId = useId()+ return (+ <form+ className="flex max-h-[80dvh] flex-col"+ onSubmit={(event) => {+ event.preventDefault()+ const content = new FormData(event.currentTarget).get('feedback-content')+ onSubmit(typeof content === 'string' ? content : '')+ }}+ >+ <div className="relative shrink-0 p-6 pr-14 pb-3">+ <DialogTitle className="title-2xl-semi-bold text-text-primary">+ {t(($) => $['feedback.title'], { ns: 'common' }) || 'Provide Feedback'}+ </DialogTitle>+ <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">+ {t(($) => $['feedback.subtitle'], { ns: 'common' }) ||+ 'Please tell us what went wrong with this response'}+ </DialogDescription>+ <DialogClose+ disabled={isSubmitting}+ render={+ <IconButton+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}+ size="lg"+ className="absolute top-5 right-5"+ >+ <span aria-hidden className="i-ri-close-line size-4" />+ </IconButton>+ }+ />+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto px-6 py-3">+ <label+ htmlFor={feedbackTextareaId}+ className="mb-2 block system-sm-semibold text-text-secondary"+ >+ {t(($) => $['feedback.content'], { ns: 'common' }) || 'Feedback Content'}+ </label>+ <Textarea+ id={feedbackTextareaId}+ name="feedback-content"+ readOnly={isSubmitting}+ placeholder={+ t(($) => $['feedback.placeholder'], { ns: 'common' }) ||+ 'Please describe what went wrong or how we can improve…'+ }+ rows={4}+ className="w-full"+ />+ </div>+ <div className="flex shrink-0 justify-end p-6 pt-5">+ <DialogClose disabled={isSubmitting} render={<Button />}>+ {t(($) => $['operation.cancel'], { ns: 'common' }) || 'Cancel'}+ </DialogClose>+ <Button type="submit" className="ml-2" variant="primary" loading={isSubmitting}>+ {t(($) => $['operation.submit'], { ns: 'common' }) || 'Submit'}+ </Button>+ </div>+ </form>+ )+}+function Operation({answerActionPosition = 'auto',item,@@ -103,16 +173,13 @@ function Operation({} = useChatContext()const [isShowReplyModal, setIsShowReplyModal] = useState(false)// Submitting replaces the dialog trigger with the current rating button.- const userFeedbackRef = useRef<HTMLButtonElement>(null)- const adminFeedbackRef = useRef<HTMLButtonElement>(null)- const [isShowFeedbackModal, setIsShowFeedbackModal] = useState(false)- const [feedbackContent, setFeedbackContent] = useState('')+ const feedbackRef = useRef<HTMLButtonElement>(null)+ const feedbackActionsRef = useRef<DialogActions>(null)+ const [isSubmittingFeedback, setIsSubmittingFeedback] = useState(false)const { id, isOpeningStatement, annotation, feedback, adminFeedback, humanInputFormDataList } =itemconst [userFeedbackOverride, setUserFeedbackOverride] = useState<Feedback>()const [adminFeedbackOverride, setAdminFeedbackOverride] = useState<Feedback>()- const [feedbackTarget, setFeedbackTarget] = useState<'user' | 'admin'>('user')- const feedbackTextareaId = useId()const content = getPublicResponseContent(item)const hasPublicContent = !!content.trim()@@ -187,15 +254,15 @@ function Operation({void handleFeedback('like', undefined, target)}- const handleFeedbackSubmit = async () => {- const succeeded = await handleFeedback('dislike', feedbackContent, feedbackTarget)- if (!succeeded) return-- setIsShowFeedbackModal(false)- }-- const handleFeedbackCancel = () => {- setIsShowFeedbackModal(false)+ const handleFeedbackSubmit = async (content: string) => {+ setIsSubmittingFeedback(true)+ const succeeded = await handleFeedback(+ 'dislike',+ content,+ config?.supportAnnotation ? 'admin' : 'user',+ )+ setIsSubmittingFeedback(false)+ if (succeeded) feedbackActionsRef.current?.close()}const operationWidth = useMemo(() => {@@ -239,10 +306,10 @@ function Operation({data-testid="operation-bar"><Dialog- open={isShowFeedbackModal}- onOpenChange={setIsShowFeedbackModal}- onOpenChangeComplete={(open) => {- if (!open) setFeedbackContent('')+ actionsRef={feedbackActionsRef}+ onOpenChange={(open, eventDetails) => {+ if (!open && isSubmittingFeedback && eventDetails.reason !== 'imperative-action')+ eventDetails.cancel()}}>{shouldShowUserFeedbackBar && !humanInputFormDataList?.length && (@@ -257,7 +324,7 @@ function Operation({content={buildFeedbackTooltip(displayUserFeedback, userFeedbackLabel)}><Toggle- ref={userFeedbackRef}+ ref={feedbackRef}className={displayUserFeedback?.rating === 'like'? accentPressedClassName@@ -293,8 +360,7 @@ function Operation({}/><DialogTrigger- ref={userFeedbackRef}- onClick={() => setFeedbackTarget('user')}+ ref={feedbackRef}render={<IconButton aria-label={`${userFeedbackLabel}: ${dislikeLabel}`}><span aria-hidden="true" className="i-ri-thumb-down-line size-4" />@@ -347,7 +413,7 @@ function Operation({content={buildFeedbackTooltip(displayAdminFeedback, adminFeedbackLabel)}><Toggle- ref={adminFeedbackRef}+ ref={feedbackRef}className={displayAdminFeedback?.rating === 'like'? accentPressedClassName@@ -390,8 +456,7 @@ function Operation({content={buildFeedbackTooltip(displayAdminFeedback, adminFeedbackLabel)}><DialogTrigger- ref={adminFeedbackRef}- onClick={() => setFeedbackTarget('admin')}+ ref={feedbackRef}render={<IconButton aria-label={`${adminFeedbackLabel}: ${dislikeLabel}`}><span aria-hidden="true" className="i-ri-thumb-down-line size-4" />@@ -404,60 +469,11 @@ function Operation({</div>)}<DialogContent- finalFocus={feedbackTarget === 'user' ? userFeedbackRef : adminFeedbackRef}+ finalFocus={feedbackRef}backdropProps={{ forceRender: true }}className="p-0">- <div className="flex max-h-[80dvh] flex-col">- <div className="relative shrink-0 p-6 pr-14 pb-3">- <DialogTitle className="title-2xl-semi-bold text-text-primary">- {t(($) => $['feedback.title'], { ns: 'common' }) || 'Provide Feedback'}- </DialogTitle>- <DialogDescription className="mt-1 system-xs-regular text-text-tertiary">- {t(($) => $['feedback.subtitle'], { ns: 'common' }) ||- 'Please tell us what went wrong with this response'}- </DialogDescription>- <DialogClose- render={- <IconButton- aria-label={t(($) => $['operation.close'], { ns: 'common' })}- size="lg"- className="absolute top-5 right-5"- >- <span aria-hidden className="i-ri-close-line size-4" />- </IconButton>- }- />- </div>- <div className="min-h-0 flex-1 overflow-y-auto px-6 py-3">- <label- htmlFor={feedbackTextareaId}- className="mb-2 block system-sm-semibold text-text-secondary"- >- {t(($) => $['feedback.content'], { ns: 'common' }) || 'Feedback Content'}- </label>- <Textarea- id={feedbackTextareaId}- name="feedback-content"- value={feedbackContent}- onValueChange={(value) => setFeedbackContent(value)}- placeholder={- t(($) => $['feedback.placeholder'], { ns: 'common' }) ||- 'Please describe what went wrong or how we can improve…'- }- rows={4}- className="w-full"- />- </div>- <div className="flex shrink-0 justify-end p-6 pt-5">- <Button onClick={handleFeedbackCancel}>- {t(($) => $['operation.cancel'], { ns: 'common' }) || 'Cancel'}- </Button>- <Button className="ml-2" variant="primary" onClick={handleFeedbackSubmit}>- {t(($) => $['operation.submit'], { ns: 'common' }) || 'Submit'}- </Button>- </div>- </div>+ <FeedbackForm isSubmitting={isSubmittingFeedback} onSubmit={handleFeedbackSubmit} /></DialogContent></Dialog>{availableLogAction && !isOpeningStatement && (diff --git a/web/app/components/base/chat/chat/type.ts b/web/app/components/base/chat/chat/type.tsindex cfc20d68386..04f32f79f4f 100644--- a/web/app/components/base/chat/chat/type.ts+++ b/web/app/components/base/chat/chat/type.ts@@ -16,7 +16,7 @@ export type FeedbackType = {content?: string | null}-export type FeedbackFunc = (messageId: string, feedback: FeedbackType) => Promise<any>+export type FeedbackFunc = (messageId: string, feedback: FeedbackType) => Promise<void>export type SubmitAnnotationFunc = (messageId: string, content: string) => Promise<any>export type ToolInfoInThought = {