Commit 0f3b9f87 by liimin

refactor(chat): 优化聊天组件结构

- 移除未使用的 Operation 组件
- 添加 LoadingAvatar 组件以显示加载状态
- 简化 Answer 组件的结构
- 删除多余的注释和未使用的代码
1 parent d6af94d7
export const markdownContent = `
# Heading 1
## Heading 2
### Heading 3
#### Heading 4
##### Heading 5
###### Heading 6
# Basic markdown content.
Should support **bold**, *italic*, and ~~strikethrough~~.
Should support [links](https://www.google.com).
Should support inline \`code\` blocks.
# Number list
1. First item
2. Second item
3. Third item
# Bullet list
- First item
- Second item
- Third item
# Link
[Google](https://www.google.com)
# Image
![Alt text](https://picsum.photos/200/300)
# Table
| Column 1 | Column 2 | Column 3 |
| -------- | -------- | -------- |
| Cell 1 | Cell 2 | Cell 3 |
| Cell 4 | Cell 5 | Cell 6 |
| Cell 7 | Cell 8 | Cell 9 |
# Code
\`\`\`JavaScript
const code = "code"
\`\`\`
# Blockquote
> This is a blockquote.
# Horizontal rule
---
`
export const markdownContentSVG = `
\`\`\`svg
<svg width="400" height="600" xmlns="http://www.w3.org/2000/svg">
<rect width="100%" height="100%" fill="#F0F8FF"/>
<text x="50%" y="60" font-family="楷体" font-size="32" fill="#4682B4" text-anchor="middle">创意Logo设计</text>
<line x1="50" y1="80" x2="350" y2="80" stroke="#B0C4DE" stroke-width="2"/>
<text x="50%" y="120" font-family="Arial" font-size="24" fill="#708090" text-anchor="middle">科研</text>
<text x="50%" y="150" font-family="MS Mincho" font-size="20" fill="#778899" text-anchor="middle">科学研究</text>
<text x="50%" y="200" font-family="汇文明朝体" font-size="18" fill="#696969" text-anchor="middle">
<tspan x="50%" dy="25">探索未知的灯塔,</tspan>
<tspan x="50%" dy="25">照亮人类前进的道路。</tspan>
<tspan x="50%" dy="25">科研,是永不熄灭的好奇心,</tspan>
<tspan x="50%" dy="25">也是推动世界进步的引擎。</tspan>
</text>
<circle cx="200" cy="400" r="80" fill="none" stroke="#4169E1" stroke-width="3"/>
<line x1="200" y1="320" x2="200" y2="480" stroke="#4169E1" stroke-width="3"/>
<line x1="120" y1="400" x2="280" y2="400" stroke="#4169E1" stroke-width="3"/>
<text x="50%" y="550" font-family="微软雅黑" font-size="16" fill="#1E90FF" text-anchor="middle">探索 • 创新 • 进步</text>
</svg>
\`\`\`
`
import type { WorkflowProcess } from '@/app/components/base/chat/types'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
export const mockedWorkflowProcess = {
status: WorkflowRunningStatus.Succeeded,
resultText: 'Hello, how can I assist you today?',
tracing: [
{
extras: {},
id: 'f6337dc9-e280-4915-965f-10b0552dd917',
node_id: '1724232060789',
node_type: 'start',
title: 'Start',
index: 1,
predecessor_node_id: null,
inputs: {
'sys.query': 'hi',
'sys.files': [],
'sys.conversation_id': '92ce0a3e-8f15-43d1-b31d-32716c4b10a7',
'sys.user_id': 'fbff43f9-d5a4-4e85-b63b-d3a91d806c6f',
'sys.dialogue_count': 1,
'sys.app_id': 'b2e8906a-aad3-43a0-9ace-0e44cc7315e1',
'sys.workflow_id': '70004abe-561f-418b-b9e8-8c957ce55140',
'sys.workflow_run_id': '69db9267-aaee-42e1-9581-dbfb67e8eeb5',
},
process_data: null,
outputs: {
'sys.query': 'hi',
'sys.files': [],
'sys.conversation_id': '92ce0a3e-8f15-43d1-b31d-32716c4b10a7',
'sys.user_id': 'fbff43f9-d5a4-4e85-b63b-d3a91d806c6f',
'sys.dialogue_count': 1,
'sys.app_id': 'b2e8906a-aad3-43a0-9ace-0e44cc7315e1',
'sys.workflow_id': '70004abe-561f-418b-b9e8-8c957ce55140',
'sys.workflow_run_id': '69db9267-aaee-42e1-9581-dbfb67e8eeb5',
},
status: 'succeeded',
error: null,
elapsed_time: 0.035744,
execution_metadata: null,
created_at: 1728980002,
finished_at: 1728980002,
files: [],
parallel_id: null,
parallel_start_node_id: null,
parent_parallel_id: null,
parent_parallel_start_node_id: null,
iteration_id: null,
loop_id: null,
},
{
extras: {},
id: '92204d8d-4198-4c46-aa02-c2754b11dec9',
node_id: 'llm',
node_type: 'llm',
title: 'LLM',
index: 2,
predecessor_node_id: '1724232060789',
inputs: null,
process_data: {
model_mode: 'chat',
prompts: [
{
role: 'system',
text: 'hi',
files: [],
},
{
role: 'user',
text: 'hi',
files: [],
},
],
model_provider: 'openai',
model_name: 'gpt-4o-mini',
},
outputs: {
text: 'Hello! How can I assist you today?',
usage: {
prompt_tokens: 13,
prompt_unit_price: '0.15',
prompt_price_unit: '0.000001',
prompt_price: '0.0000020',
completion_tokens: 9,
completion_unit_price: '0.60',
completion_price_unit: '0.000001',
completion_price: '0.0000054',
total_tokens: 22,
total_price: '0.0000074',
currency: 'USD',
latency: 1.8902503330027685,
},
finish_reason: 'stop',
},
status: 'succeeded',
error: null,
elapsed_time: 5.089409,
execution_metadata: {
total_tokens: 22,
total_price: '0.0000074',
currency: 'USD',
},
created_at: 1728980002,
finished_at: 1728980007,
files: [],
parallel_id: null,
parallel_start_node_id: null,
parent_parallel_id: null,
parent_parallel_start_node_id: null,
iteration_id: null,
loop_id: null,
},
{
extras: {},
id: '7149bac6-60f9-4e06-a5ed-1d9d3764c06b',
node_id: 'answer',
node_type: 'answer',
title: 'Answer',
index: 3,
predecessor_node_id: 'llm',
inputs: null,
process_data: null,
outputs: {
answer: 'Hello! How can I assist you today?',
},
status: 'succeeded',
error: null,
elapsed_time: 0.015339,
execution_metadata: null,
created_at: 1728980007,
finished_at: 1728980007,
parallel_id: null,
parallel_start_node_id: null,
parent_parallel_id: null,
parent_parallel_start_node_id: null,
},
],
} as unknown as WorkflowProcess
import type { FC } from 'react'
import { memo } from 'react'
import type {
ChatItem,
} from '../../types'
import { Markdown } from '@/app/components/base/markdown'
import Thought from '@/app/components/base/chat/chat/thought'
import { FileList } from '@/app/components/base/file-uploader'
import { getProcessedFilesFromResponse } from '@/app/components/base/file-uploader/utils'
type AgentContentProps = {
item: ChatItem
responding?: boolean
content?: string
}
const AgentContent: FC<AgentContentProps> = ({
item,
responding,
content,
}) => {
const {
annotation,
agent_thoughts,
} = item
if (annotation?.logAnnotation)
return <Markdown content={annotation?.logAnnotation.content || ''} />
return (
<div>
{content ? <Markdown content={content} /> : agent_thoughts?.map((thought, index) => (
<div key={index} className='px-2 py-1'>
{thought.thought && (
<Markdown content={thought.thought} />
)}
{/* {item.tool} */}
{/* perhaps not use tool */}
{!!thought.tool && (
<Thought
thought={thought}
isFinished={!!thought.observation || !responding}
/>
)}
{
!!thought.message_files?.length && (
<FileList
files={getProcessedFilesFromResponse(thought.message_files.map((item: any) => ({ ...item, related_id: item.id })))}
showDeleteAction={false}
showDownloadAction={true}
canPreview={true}
/>
)
}
</div>
))}
</div>
)
}
export default memo(AgentContent)
import type { FC } from 'react'
import { memo } from 'react'
import type { ChatItem } from '../../types'
import { Markdown } from '@/app/components/base/markdown'
import cn from '@/utils/classnames'
type BasicContentProps = {
item: ChatItem
}
const BasicContent: FC<BasicContentProps> = ({ item }) => {
const { id, annotation, content } = item
// console.log(content)
if (annotation?.logAnnotation) return <Markdown content={annotation?.logAnnotation.content || ''} />
return <Markdown className={cn(item.isError && '!text-[#F04438]')} content={content} />
}
const MemoizedBasicContent = memo(BasicContent, (prev, next) => {
return prev.item.content === next.item.content
})
export default memo(MemoizedBasicContent)
import type { Meta, StoryObj } from '@storybook/react'
import type { ChatItem } from '../../types'
import { mockedWorkflowProcess } from './__mocks__/workflowProcess'
import { markdownContent } from './__mocks__/markdownContent'
import { markdownContentSVG } from './__mocks__/markdownContentSVG'
import Answer from '.'
const meta = {
title: 'Base/Chat Answer',
component: Answer,
parameters: {
layout: 'fullscreen',
},
tags: ['autodocs'],
argTypes: {
noChatInput: { control: 'boolean', description: 'If set to true, some buttons that are supposed to be shown on hover will not be displayed.' },
responding: { control: 'boolean', description: 'Indicates if the answer is being generated.' },
showPromptLog: { control: 'boolean', description: 'If set to true, the prompt log button will be shown on hover.' },
},
args: {
noChatInput: false,
responding: false,
showPromptLog: false,
},
} satisfies Meta<typeof Answer>
export default meta
type Story = StoryObj<typeof meta>
const mockedBaseChatItem = {
id: '1',
isAnswer: true,
content: 'Hello, how can I assist you today?',
} satisfies ChatItem
export const Basic: Story = {
args: {
item: mockedBaseChatItem,
question: mockedBaseChatItem.content,
index: 0,
},
render: (args) => {
return <div className="w-full px-10 py-5">
<Answer {...args} />
</div>
},
}
export const WithWorkflowProcess: Story = {
args: {
item: {
...mockedBaseChatItem,
workflowProcess: mockedWorkflowProcess,
},
question: mockedBaseChatItem.content,
index: 0,
},
render: (args) => {
return <div className="w-full px-10 py-5">
<Answer {...args} />
</div>
},
}
export const WithMarkdownContent: Story = {
args: {
item: {
...mockedBaseChatItem,
content: markdownContent,
},
question: mockedBaseChatItem.content,
index: 0,
},
render: (args) => {
return <div className="w-full px-10 py-5">
<Answer {...args} />
</div>
},
}
export const WithMarkdownSVG: Story = {
args: {
item: {
...mockedBaseChatItem,
content: markdownContentSVG,
},
question: mockedBaseChatItem.content,
index: 0,
},
render: (args) => {
return <div className="w-full px-10 py-5">
<Answer {...args} />
</div>
},
}
import type { FC, ReactNode } from 'react'
import { memo, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import type { ChatConfig, ChatItem } from '../../types'
import Operation from './operation'
import AgentContent from './agent-content'
import BasicContent from './basic-content'
import SuggestedQuestions from './suggested-questions'
import More from './more'
// import WorkflowProcessItem from "./workflow-process";
import LoadingAnim from '@/app/components/base/chat/chat/loading-anim'
import Citation from '@/app/components/base/chat/chat/citation'
// import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item";
import type { AppData } from '@/models/share'
import AnswerIcon from '@/app/components/base/answer-icon'
import { ChevronRight } from '@/app/components/base/icons/src/vender/line/arrows'
import cn from '@/utils/classnames'
import { FileList } from '@/app/components/base/file-uploader'
import { useChatContext } from '../context'
import { useChatStore } from '../../chat-with-history/store'
type AnswerProps = {
item: ChatItem
question: string
index: number
answerIcon?: ReactNode
showPromptLog?: boolean
isLast?: boolean
chatAnswerContainerInner?: string
noChatInput?: boolean
switchSibling?: (siblingMessageId: string) => void
}
const Answer: FC<AnswerProps> = ({
item,
question,
index,
answerIcon,
showPromptLog,
isLast,
chatAnswerContainerInner,
noChatInput,
}) => {
const { t } = useTranslation()
const { content, citation, agent_thoughts, more, annotation, workflowProcess, allFiles, message_files } = item
const hasAgentThoughts = !!agent_thoughts?.length
// console.log(content)
const [containerWidth, setContainerWidth] = useState(0)
const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const { config, isResponding } = useChatContext()
// const [config,isResponding] = useChatStore(state =>[state.config,state.isResponding])
const responding = isLast && isResponding
const getContainerWidth = () => {
if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16)
}
useEffect(() => {
getContainerWidth()
}, [])
const getContentWidth = () => {
if (contentRef.current) setContentWidth(contentRef.current?.clientWidth)
}
useEffect(() => {
if (!responding) getContentWidth()
}, [responding])
// Recalculate contentWidth when content changes (e.g., SVG preview/source toggle)
useEffect(() => {
if (!containerRef.current) return
const resizeObserver = new ResizeObserver(() => {
getContentWidth()
})
resizeObserver.observe(containerRef.current)
return () => {
resizeObserver.disconnect()
}
}, [])
return (
<div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">
{answerIcon || <AnswerIcon imageUrl={''} />}
{responding && (
<div className="absolute -left-[3px] -top-[3px] flex h-4 w-4 items-center rounded-full border-[0.5px] border-divider-subtle bg-background-section-burn pl-[6px] shadow-xs">
<LoadingAnim type="avatar" />
</div>
)}
</div>
<div className="chat-answer-container group ml-4 w-0 grow pb-2" ref={containerRef}>
<div className={cn('group relative pr-14', chatAnswerContainerInner)}>
<div
ref={contentRef}
className={cn(
'body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary',
workflowProcess && 'w-full',
)}>
{!responding && (
<Operation
hasWorkflowProcess={!!workflowProcess}
maxSize={containerWidth - contentWidth - 4}
contentWidth={contentWidth}
item={item}
isLast={isLast}
question={question}
index={index}
showPromptLog={showPromptLog}
noChatInput={noChatInput}
/>
)}
{/** Render the normal steps */}
{/* {workflowProcess && !hideProcessDetail && (
<WorkflowProcessItem
data={workflowProcess}
item={item}
hideProcessDetail={hideProcessDetail}
/>
)} */}
{/** Hide workflow steps by it's settings in siteInfo */}
{/* {workflowProcess && hideProcessDetail && appData && (
<WorkflowProcessItem
data={workflowProcess}
item={item}
hideProcessDetail={hideProcessDetail}
readonly={!appData.site.show_workflow_steps}
/>
)} */}
{responding && !content && !hasAgentThoughts && (
<div className="flex h-5 w-6 items-center justify-center">
<LoadingAnim type="text" />
</div>
)}
{content && !hasAgentThoughts && <BasicContent item={item}/>}
{/* {hasAgentThoughts && <AgentContent item={item} responding={responding} content={content} />} */}
{/* {!!allFiles?.length && (
<FileList className="my-1" files={allFiles} showDeleteAction={false} showDownloadAction canPreview />
)}
{!!message_files?.length && (
<FileList className="my-1" files={message_files} showDeleteAction={false} showDownloadAction canPreview />
)} */}
{/* {annotation?.id && annotation.authorName && (
<EditTitle
className="mt-1"
title={t("appAnnotation.editBy", {
author: annotation.authorName,
})}
/>
)} */}
{/* <SuggestedQuestions item={item} /> */}
{/* {!!citation?.length && !responding && (
<Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />
)} */}
{/* {item.siblingCount && item.siblingCount > 1 && item.siblingIndex !== undefined && (
<div className="flex items-center justify-center pt-3.5 text-sm">
<button className={`${item.prevSibling ? 'opacity-100' : 'opacity-30'}`} disabled={!item.prevSibling} onClick={() => item.prevSibling && switchSibling?.(item.prevSibling)}>
<ChevronRight className="h-[14px] w-[14px] rotate-180 text-text-primary" />
</button>
<span className="px-2 text-xs text-text-primary">
{item.siblingIndex + 1} / {item.siblingCount}
</span>
<button className={`${item.nextSibling ? 'opacity-100' : 'opacity-30'}`} disabled={!item.nextSibling} onClick={() => item.nextSibling && switchSibling?.(item.nextSibling)}>
<ChevronRight className="h-[14px] w-[14px] text-text-primary" />
</button>
</div>
)} */}
</div>
</div>
<More more={more} />
</div>
</div>
)
}
// const AnswerMemo = memo(Answer, (prevProps: AnswerProps, nextProps: AnswerProps) => {
// return true
// // return (
// // !nextProps.item.content ||
// // (prevProps.item.content === nextProps.item.content &&
// // prevProps.isLast === nextProps.isLast &&
// // prevProps.responding === nextProps.responding)
// // )
// })
export default memo(Answer)
import type { FC, ReactNode } from 'react'
import { memo, useMemo } from 'react'
import type { ChatConfig, ChatItem } from '../../types'
import BasicContent from './basic-content'
import SuggestedQuestions from './suggested-questions'
// import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item";
import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames'
import { useChatContext } from '../context'
import { useChatStore } from '../../chat-with-history/store'
type InitQuestionsProps = {
// config: ChatConfig
answerIcon: ReactNode
chatAnswerContainerInner?: string
}
const InitQuestions: FC<InitQuestionsProps> = ({ answerIcon, chatAnswerContainerInner }) => {
// const config = useChatStore(state => state.config)
const {config} = useChatContext()
const questions = useMemo(() => {
const { suggested_questions, initial_message } = config
const suggestedQuestions = suggested_questions
?.filter(q => !!q && q.trim())
.sort(() => Math.random() - 0.5)
.slice(0, 3)
const initQuestions: ChatItem = {
content: initial_message || '',
suggestedQuestions,
isAnswer: true,
id: 'initial_message',
}
return initQuestions
}, [config.initial_message])
if(!questions.content) return <></>
return (
<div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">{answerIcon || <AnswerIcon imageUrl={''} />}</div>
<div className="chat-answer-container group ml-4 w-0 grow pb-2">
<div className={cn('group relative pr-14', chatAnswerContainerInner)}>
<div className={cn('body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary')}>
{<BasicContent item={questions} />}
{<SuggestedQuestions item={questions} />}
</div>
</div>
</div>
</div>
)
}
export default memo(InitQuestions)
/*
* @Author: liimin 17653212@qq.com
* @Date: 2025-04-16 18:17:38
* @LastEditors: liimin 17653212@qq.com
* @LastEditTime: 2025-05-12 10:33:11
* @FilePath: \ai-assistant\app\components\base\chat\chat\answer\more.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import type { FC } from 'react'
import { memo } from 'react'
import { useTranslation } from 'react-i18next'
import type { ChatItem } from '../../types'
import { formatNumber } from '@/utils/format'
type MoreProps = {
more: ChatItem['more']
}
const More: FC<MoreProps> = ({
more,
}) => {
const { t } = useTranslation()
return (
<div className='system-xs-regular mt-1 flex items-center text-text-quaternary opacity-0 group-hover:opacity-100'>
{
more && (
<>
<div
className='mr-2 max-w-[33.3%] shrink-0 truncate'
title={`${t('appLog.detail.timeConsuming')} ${more.latency}${t('appLog.detail.second')}`}
>
{`${t('appLog.detail.timeConsuming')} ${more.latency}${t('appLog.detail.second')}`}
</div>
<div
className='max-w-[33.3%] shrink-0 truncate'
title={`${t('appLog.detail.tokenCost')} ${formatNumber(more.tokens)}`}
>
{`${t('appLog.detail.tokenCost')} ${formatNumber(more.tokens)}`}
</div>
<div className='mx-2 shrink-0'>·</div>
<div
className='max-w-[33.3%] shrink-0 truncate'
title={more.time}
>
{more.time}
</div>
</>
)
}
</div>
)
}
export default memo(More)
......@@ -2,15 +2,14 @@ import type { FC } from 'react'
import { memo, useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiClipboardLine, RiEditLine, RiResetLeftLine, RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import type { ChatItem } from '../../types'
import { useChatContext } from '../context'
import type { ChatItem } from '../../../types'
import { useChatContext } from '../../context'
import copy from 'copy-to-clipboard'
import Toast from '@/app/components/base/toast'
import Log from '@/app/components/base/chat/chat/log'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
import NewAudioButton from '@/app/components/base/new-audio-button'
import cn from '@/utils/classnames'
import { useChatStore } from '../../chat-with-history/store'
type OperationProps = {
item: ChatItem
......
/*
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17
* @LastEditors: limin
* @LastEditTime: 2025-07-08 18:09:11
* @FilePath: \ai-assistant\app\components\base\chat\chat\answer\suggested-questions.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import type { FC } from 'react'
import { memo, useMemo } from 'react'
import type { ChatItem } from '../../types'
import { useChatContext } from '../context'
import Button from '@/app/components/base/button/next-button'
// import { AUTO_INPUT } from '@/app/components/base/chat/constants'
import { InputMessageType } from '../../types'
import { useChatStore } from '../../chat-with-history/store'
type SuggestedQuestionsProps = {
item: ChatItem
}
const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => {
// const sendMessage = useChatStore(state=>state.sendMessage)
const { onSend:sendMessage } = useChatContext()
const { suggestedQuestions } = item
if (!suggestedQuestions?.length) return null
// const questionList = useMemo(() => {
// const suggestedList = suggestedQuestions.filter(q => !!q && q.trim()).sort(() => Math.random() - 0.5)
// return suggestedList.slice(0, 3)
// }, [suggestedQuestions])
return (
<div className="w-[fit-content]">
{suggestedQuestions.map((question, index) => (
<Button
key={index}
text={question}
onClick={() => sendMessage?.(question, InputMessageType.QUESTION_IN_WELCOME )}></Button>
))}
</div>
)
}
const MemoizedSuggestedQuestions = memo(SuggestedQuestions, (prev, next) => {
return prev.item.suggestedQuestions?.length === next.item.suggestedQuestions?.length
})
export default MemoizedSuggestedQuestions
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import {
RiArrowDownSLine,
RiArrowRightSLine,
RiHammerFill,
RiLoader2Line,
} from '@remixicon/react'
import type { ToolInfoInThought } from '../type'
import cn from '@/utils/classnames'
type ToolDetailProps = {
payload: ToolInfoInThought
}
const ToolDetail = ({
payload,
}: ToolDetailProps) => {
const { t } = useTranslation()
const { name, label, input, isFinished, output } = payload
const toolLabel = name.startsWith('dataset_') ? t('dataset.knowledge') : label
const [expand, setExpand] = useState(false)
return (
<div
className={cn(
'rounded-xl',
!expand && 'border-l-[0.25px] border-components-panel-border bg-workflow-process-bg',
expand && 'border-[0.5px] border-components-panel-border-subtle bg-background-section-burn',
)}
>
<div
className={cn(
'system-xs-medium flex cursor-pointer items-center px-2.5 py-2 text-text-tertiary',
expand && 'pb-1.5',
)}
onClick={() => setExpand(!expand)}
>
{isFinished && <RiHammerFill className='mr-1 h-3.5 w-3.5' />}
{!isFinished && <RiLoader2Line className='mr-1 h-3.5 w-3.5 animate-spin' />}
{t(`tools.thought.${isFinished ? 'used' : 'using'}`)}
<div className='mx-1 text-text-secondary'>{toolLabel}</div>
{!expand && <RiArrowRightSLine className='h-4 w-4' />}
{expand && <RiArrowDownSLine className='ml-auto h-4 w-4' />}
</div>
{
expand && (
<>
<div className='mx-1 mb-0.5 rounded-[10px] bg-components-panel-on-panel-item-bg text-text-secondary'>
<div className='system-xs-semibold-uppercase flex h-7 items-center justify-between px-2 pt-1'>
{t('tools.thought.requestTitle')}
</div>
<div className='code-xs-regular break-words px-3 pb-2 pt-1'>
{input}
</div>
</div>
<div className='mx-1 mb-1 rounded-[10px] bg-components-panel-on-panel-item-bg text-text-secondary'>
<div className='system-xs-semibold-uppercase flex h-7 items-center justify-between px-2 pt-1'>
{t('tools.thought.responseTitle')}
</div>
<div className='code-xs-regular break-words px-3 pb-2 pt-1'>
{output}
</div>
</div>
</>
)
}
</div>
)
}
export default ToolDetail
import {
useEffect,
useState,
} from 'react'
import {
RiArrowRightSLine,
RiErrorWarningFill,
RiLoader2Line,
} from '@remixicon/react'
import { useTranslation } from 'react-i18next'
import type { ChatItem, WorkflowProcess } from '../../types'
import TracingPanel from '@/app/components/workflow/run/tracing-panel'
import cn from '@/utils/classnames'
import { CheckCircle } from '@/app/components/base/icons/src/vender/solid/general'
import { WorkflowRunningStatus } from '@/app/components/workflow/types'
type WorkflowProcessProps = {
data: WorkflowProcess
item?: ChatItem
expand?: boolean
hideInfo?: boolean
hideProcessDetail?: boolean
readonly?: boolean
}
const WorkflowProcessItem = ({
data,
expand = false,
hideInfo = false,
hideProcessDetail = false,
readonly = false,
}: WorkflowProcessProps) => {
const { t } = useTranslation()
const [collapse, setCollapse] = useState(!expand)
const running = data.status === WorkflowRunningStatus.Running
const succeeded = data.status === WorkflowRunningStatus.Succeeded
const failed = data.status === WorkflowRunningStatus.Failed || data.status === WorkflowRunningStatus.Stopped
useEffect(() => {
setCollapse(!expand)
}, [expand])
return (
<div
className={cn(
'-mx-1 rounded-xl px-2.5',
collapse ? 'border-l-[0.25px] border-components-panel-border py-[7px]' : 'border-[0.5px] border-components-panel-border-subtle px-1 pb-1 pt-[7px]',
running && !collapse && 'bg-background-section-burn',
succeeded && !collapse && 'bg-state-success-hover',
failed && !collapse && 'bg-state-destructive-hover',
collapse && 'bg-workflow-process-bg',
)}
>
<div
className={cn('flex cursor-pointer items-center', !collapse && 'px-1.5', readonly && 'cursor-default')}
onClick={() => !readonly && setCollapse(!collapse)}
>
{
running && (
<RiLoader2Line className='mr-1 h-3.5 w-3.5 shrink-0 animate-spin text-text-tertiary' />
)
}
{
succeeded && (
<CheckCircle className='mr-1 h-3.5 w-3.5 shrink-0 text-text-success' />
)
}
{
failed && (
<RiErrorWarningFill className='mr-1 h-3.5 w-3.5 shrink-0 text-text-destructive' />
)
}
<div className={cn('system-xs-medium text-text-secondary', !collapse && 'grow')}>
{t('workflow.common.workflowProcess')}
</div>
{!readonly && <RiArrowRightSLine className={cn('ml-1 h-4 w-4 text-text-tertiary', !collapse && 'rotate-90')} />}
</div>
{
!collapse && !readonly && (
<div className='mt-1.5'>
{
<TracingPanel
list={data.tracing}
hideNodeInfo={hideInfo}
hideNodeProcessDetail={hideProcessDetail}
/>
}
</div>
)
}
</div>
)
}
export default WorkflowProcessItem
import type { FC } from 'react'
import { memo } from 'react'
import Operation from '../operation'
import BasicContent from '../basic-content'
import SuggestedQuestions from '../suggested-questions'
import Citation from '@/app/components/base/chat/chat/citation'
interface AnswerContentProps {
hasWorkflowProcess: boolean
maxSize: number
contentWidth: number
item: any
isLast?: boolean
question: string
index: number
showPromptLog?: boolean
noChatInput?: boolean
}
const AnswerContent: FC<AnswerContentProps> = memo(({
hasWorkflowProcess,
maxSize,
contentWidth,
item,
isLast,
question,
index,
showPromptLog,
noChatInput,
}) => {
const { config } = item
return (
<>
<Operation
hasWorkflowProcess={hasWorkflowProcess}
maxSize={maxSize}
contentWidth={contentWidth}
item={item}
isLast={isLast}
question={question}
index={index}
showPromptLog={showPromptLog}
noChatInput={noChatInput}
/>
<BasicContent item={item} />
<SuggestedQuestions item={item} />
{!!item.citation?.length && <Citation data={item.citation} showHitInfo={config?.supportCitationHitInfo} />}
</>
)
})
export default AnswerContent
\ No newline at end of file
import type { FC } from 'react'
import { memo } from 'react'
import LoadingAnim from '@/app/components/base/chat/chat/loading-anim'
import { useChatContext } from '../../context'
type AnswerProps = {
isLast?: boolean
}
const LoadingAvatar: FC<AnswerProps> = ({ isLast }) => {
const { isResponding } = useChatContext()
const responding = isLast && isResponding
return (
<>
{responding && (
<div className="absolute -left-[3px] -top-[3px] flex h-4 w-4 items-center rounded-full border-[0.5px] border-divider-subtle bg-background-section-burn pl-[6px] shadow-xs">
<LoadingAnim type="avatar" />
</div>
)}
</>
)
}
export default memo(LoadingAvatar)
import { createContext, ReactNode, useContext, useMemo } from 'react'
// 定义消息上下文类型
interface AnswerContextType {
isLast: boolean
}
// 创建上下文并设置默认值
const AnswerContext = createContext<AnswerContextType | undefined>(undefined)
// 自定义hook用于访问消息上下文
export const useAnswerContext = (): AnswerContextType => {
const context = useContext(AnswerContext)
if (!context) {
throw new Error('useAnswerContext must be used within a AnswerProvider')
}
return context
}
// 消息提供者组件
export const AnswerProvider = ({ children }: { children: ReactNode }) => {
// 提供上下文值
return <AnswerContext.Provider value={{ isLast: true }}>{children}</AnswerContext.Provider>
}
......@@ -18,6 +18,7 @@ import cn from '@/utils/classnames'
import { FileList } from '@/app/components/base/file-uploader'
import { useChatContext } from '../context'
import { useChatStore } from '../../chat-with-history/store'
import LoadingAvatar from './components/loading-avatar'
type AnswerProps = {
item: ChatItem
......@@ -43,14 +44,13 @@ const Answer: FC<AnswerProps> = ({
const { t } = useTranslation()
const { content, citation, agent_thoughts, more, annotation, workflowProcess, allFiles, message_files } = item
const hasAgentThoughts = !!agent_thoughts?.length
// console.log(content)
const [containerWidth, setContainerWidth] = useState(0)
const [contentWidth, setContentWidth] = useState(0)
const containerRef = useRef<HTMLDivElement>(null)
const contentRef = useRef<HTMLDivElement>(null)
const { config, isResponding } = useChatContext()
// const [config,isResponding] = useChatStore(state =>[state.config,state.isResponding])
const responding = isLast && isResponding
const getContainerWidth = () => {
if (containerRef.current) setContainerWidth(containerRef.current?.clientWidth + 16)
}
......@@ -81,11 +81,7 @@ const Answer: FC<AnswerProps> = ({
<div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0">
{answerIcon || <AnswerIcon imageUrl={''} />}
{responding && (
<div className="absolute -left-[3px] -top-[3px] flex h-4 w-4 items-center rounded-full border-[0.5px] border-divider-subtle bg-background-section-burn pl-[6px] shadow-xs">
<LoadingAnim type="avatar" />
</div>
)}
<LoadingAvatar isLast={isLast} />
</div>
<div className="chat-answer-container group ml-4 w-0 grow pb-2" ref={containerRef}>
<div className={cn('group relative pr-14', chatAnswerContainerInner)}>
......@@ -108,61 +104,12 @@ const Answer: FC<AnswerProps> = ({
noChatInput={noChatInput}
/>
)}
{/** Render the normal steps */}
{/* {workflowProcess && !hideProcessDetail && (
<WorkflowProcessItem
data={workflowProcess}
item={item}
hideProcessDetail={hideProcessDetail}
/>
)} */}
{/** Hide workflow steps by it's settings in siteInfo */}
{/* {workflowProcess && hideProcessDetail && appData && (
<WorkflowProcessItem
data={workflowProcess}
item={item}
hideProcessDetail={hideProcessDetail}
readonly={!appData.site.show_workflow_steps}
/>
)} */}
{responding && !content && !hasAgentThoughts && (
<div className="flex h-5 w-6 items-center justify-center">
<LoadingAnim type="text" />
</div>
)}
{content && !hasAgentThoughts && <BasicContent item={item}/>}
{/* {hasAgentThoughts && <AgentContent item={item} responding={responding} content={content} />} */}
{/* {!!allFiles?.length && (
<FileList className="my-1" files={allFiles} showDeleteAction={false} showDownloadAction canPreview />
)}
{!!message_files?.length && (
<FileList className="my-1" files={message_files} showDeleteAction={false} showDownloadAction canPreview />
)} */}
{/* {annotation?.id && annotation.authorName && (
<EditTitle
className="mt-1"
title={t("appAnnotation.editBy", {
author: annotation.authorName,
})}
/>
)} */}
{/* <SuggestedQuestions item={item} /> */}
{/* {!!citation?.length && !responding && (
<Citation data={citation} showHitInfo={config?.supportCitationHitInfo} />
)} */}
{/* {item.siblingCount && item.siblingCount > 1 && item.siblingIndex !== undefined && (
<div className="flex items-center justify-center pt-3.5 text-sm">
<button className={`${item.prevSibling ? 'opacity-100' : 'opacity-30'}`} disabled={!item.prevSibling} onClick={() => item.prevSibling && switchSibling?.(item.prevSibling)}>
<ChevronRight className="h-[14px] w-[14px] rotate-180 text-text-primary" />
</button>
<span className="px-2 text-xs text-text-primary">
{item.siblingIndex + 1} / {item.siblingCount}
</span>
<button className={`${item.nextSibling ? 'opacity-100' : 'opacity-30'}`} disabled={!item.nextSibling} onClick={() => item.nextSibling && switchSibling?.(item.nextSibling)}>
<ChevronRight className="h-[14px] w-[14px] text-text-primary" />
</button>
</div>
)} */}
{content && !hasAgentThoughts && <BasicContent item={item} />}
</div>
</div>
<More more={more} />
......@@ -170,15 +117,4 @@ const Answer: FC<AnswerProps> = ({
</div>
)
}
// const AnswerMemo = memo(Answer, (prevProps: AnswerProps, nextProps: AnswerProps) => {
// return true
// // return (
// // !nextProps.item.content ||
// // (prevProps.item.content === nextProps.item.content &&
// // prevProps.isLast === nextProps.isLast &&
// // prevProps.responding === nextProps.responding)
// // )
// })
export default memo(Answer)
import type { FC } from 'react'
import { memo } from 'react'
import { RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
interface FeedbackActiveProps {
localFeedback: any
onFeedback: (rating: 'like' | 'dislike' | null) => Promise<void>
}
const FeedbackActive: FC<FeedbackActiveProps> = ({ localFeedback, onFeedback }) => {
return (
<div className="ml-1 flex items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm">
{localFeedback?.rating === 'like' && (
<ActionButton state={ActionButtonState.Active} onClick={() => onFeedback(null)}>
<RiThumbUpLine className="h-4 w-4" />
</ActionButton>
)}
{localFeedback?.rating === 'dislike' && (
<ActionButton state={ActionButtonState.Destructive} onClick={() => onFeedback(null)}>
<RiThumbDownLine className="h-4 w-4" />
</ActionButton>
)}
</div>
)
}
export default memo(FeedbackActive)
\ No newline at end of file
import type { FC } from 'react'
import { memo } from 'react'
import { RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import ActionButton from '@/app/components/base/action-button'
interface FeedbackProps {
onFeedback: (rating: 'like' | 'dislike' | null) => Promise<void>
showLike: boolean
}
const Feedback: FC<FeedbackProps> = ({ onFeedback, showLike }) => {
return (
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex">
<ActionButton onClick={() => onFeedback('like')}>
<RiThumbUpLine className="h-4 w-4" />
</ActionButton>
<ActionButton onClick={() => onFeedback('dislike')}>
<RiThumbDownLine className="h-4 w-4" />
</ActionButton>
</div>
)
}
export default memo(Feedback)
\ No newline at end of file
import type { FC } from 'react'
import { memo, useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { RiClipboardLine, RiEditLine, RiResetLeftLine, RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import type { ChatItem } from '../../../types'
import { useChatContext } from '../../context'
import copy from 'copy-to-clipboard'
import Toast from '@/app/components/base/toast'
import Log from '@/app/components/base/chat/chat/log'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
import NewAudioButton from '@/app/components/base/new-audio-button'
import cn from '@/utils/classnames'
import FeedbackButtons from './feedback'
import ActiveFeedbackButton from './feedback-active'
import OperationButtons from './operation'
type OperationProps = {
item: ChatItem
question: string
index: number
showPromptLog?: boolean
maxSize: number
isLast?: boolean
contentWidth: number
hasWorkflowProcess: boolean
noChatInput?: boolean
}
const Operation: FC<OperationProps> = ({
item,
isLast,
question,
index,
showPromptLog,
maxSize,
contentWidth,
hasWorkflowProcess,
noChatInput,
}) => {
const { t } = useTranslation()
const { config, onFeedback, onRegenerate } = useChatContext()
const [isShowReplyModal, setIsShowReplyModal] = useState(false)
const [showLike, setShowLike] = useState(false)
const { id, isOpeningStatement, content: messageContent, annotation, feedback, adminFeedback, agent_thoughts } = item
const [localFeedback, setLocalFeedback] = useState(config?.supportAnnotation ? adminFeedback : feedback)
// 计算内容
const content = useMemo(() => {
if (agent_thoughts?.length) return agent_thoughts.reduce((acc, cur) => acc + cur.thought, '')
return messageContent
}, [agent_thoughts, messageContent])
// 判断反馈按钮是否启用
const feedbackEnabled = useMemo(
() => config?.supportFeedback && !localFeedback?.rating && !isOpeningStatement,
[config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
)
// 判断是否已点赞
const feedbackActive = useMemo(
() => config?.supportFeedback && localFeedback?.rating && !isOpeningStatement,
[config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement],
)
// 处理反馈
const handleFeedback = async (rating: 'like' | 'dislike' | null) => {
if (!config?.supportFeedback || !onFeedback || showLike) return
try {
setShowLike(true)
await onFeedback(id, { rating })
setLocalFeedback({ rating })
Toast.notify({ type: 'success', message: '成功' })
} catch (error) {
Toast.notify({ type: 'error', message: '反馈失败,请稍后再试' })
console.error('Feedback error:', error)
} finally {
setShowLike(false)
}
}
// 计算操作区域宽度
const operationWidth = useMemo(() => {
let width = 0
if (!isOpeningStatement) width += 26
if (!isOpeningStatement && showPromptLog) width += 28 + 8
if (!isOpeningStatement && config?.text_to_speech?.enabled) width += 26
if (!isOpeningStatement && config?.supportAnnotation && config?.annotation_reply?.enabled) width += 26
if (config?.supportFeedback && !localFeedback?.rating && !isOpeningStatement) width += 60 + 8
if (config?.supportFeedback && localFeedback?.rating && !isOpeningStatement) width += 28 + 8
return width
}, [
isOpeningStatement,
showPromptLog,
config?.text_to_speech?.enabled,
config?.supportAnnotation,
config?.annotation_reply?.enabled,
config?.supportFeedback,
localFeedback?.rating,
onFeedback,
])
// 判断位置是否靠左
const positionRight = useMemo(() => operationWidth < maxSize, [operationWidth, maxSize])
return (
<>
<div
className={cn(
'absolute flex justify-end gap-1',
hasWorkflowProcess && '-bottom-4 right-2',
!positionRight && '-bottom-4 right-2',
!hasWorkflowProcess && positionRight && '!top-[9px]',
!hasWorkflowProcess && positionRight ? 'left-auto' : '',
)}
style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}}>
{/* 日志展示 */}
{/* {showPromptLog && !isOpeningStatement && (
<div className="hidden group-hover:block">
<Log logItem={item} />
</div>
)} */}
{/* 操作按钮容器 */}
{!isOpeningStatement && (
<OperationButtons
config={config}
id={id}
content={content}
noChatInput={noChatInput}
isLast={isLast}
item={item}
onRegenerate={onRegenerate}
setIsShowReplyModal={setIsShowReplyModal}
/>
)}
{/* 反馈按钮 */}
{feedbackEnabled && <FeedbackButtons onFeedback={handleFeedback} showLike={showLike} />}
{/* 已点赞按钮 */}
{feedbackActive && <ActiveFeedbackButton localFeedback={localFeedback} onFeedback={handleFeedback} />}
</div>
</>
)
}
// 自定义比较函数,只比较关键 props
const areEqual = (prev: OperationProps, next: OperationProps) =>
prev.showPromptLog === next.showPromptLog &&
prev.maxSize === next.maxSize &&
prev.isLast === next.isLast &&
prev.contentWidth === next.contentWidth &&
prev.hasWorkflowProcess === next.hasWorkflowProcess &&
prev.noChatInput === next.noChatInput
export default memo(Operation, areEqual)
import type { FC } from 'react'
import { memo, useCallback } from 'react'
import { RiClipboardLine, RiEditLine, RiResetLeftLine } from '@remixicon/react'
import ActionButton from '@/app/components/base/action-button'
import NewAudioButton from '@/app/components/base/new-audio-button'
import copy from 'copy-to-clipboard'
import Toast from '@/app/components/base/toast'
interface OperationButtonsProps {
config: any
id: string
content: string
noChatInput?: boolean
isLast?: boolean
item: any
onRegenerate?: (item: any) => void
setIsShowReplyModal: (value: boolean) => void
}
const OperationButtons: FC<OperationButtonsProps> = memo(({ config, id, content, noChatInput, isLast, item, onRegenerate, setIsShowReplyModal }) => {
const handleCopy = useCallback(() => {
copy(content)
Toast.notify({
type: 'success',
message: '复制成功',
})
}, [content])
return (
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex">
{/* {config?.text_to_speech?.enabled && <NewAudioButton id={id} value={content} voice={config?.text_to_speech?.voice} />} */}
<ActionButton onClick={handleCopy}>
<RiClipboardLine className="h-4 w-4" />
</ActionButton>
{!noChatInput && isLast && (
<ActionButton onClick={() => onRegenerate?.(item)}>
<RiResetLeftLine className="h-4 w-4" />
</ActionButton>
)}
{config?.supportAnnotation && config.annotation_reply?.enabled && (
<ActionButton onClick={() => setIsShowReplyModal(true)}>
<RiEditLine className="h-4 w-4" />
</ActionButton>
)}
</div>
)
})
export default OperationButtons
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!