Feat: Add a think button to the chat box. #12742 (#12743)

### What problem does this PR solve?

Feat: Add a think button to the chat box. #12742
### Type of change


- [x] New Feature (non-breaking change which adds functionality)
This commit is contained in:
balibabu
2026-01-21 15:39:18 +08:00
committed by GitHub
parent f98abf14a8
commit e1143d40bc
12 changed files with 190 additions and 149 deletions

View File

@ -68,8 +68,9 @@ const FloatingChatWidget = () => {
// Play sound when opening // Play sound when opening
const playNotificationSound = useCallback(() => { const playNotificationSound = useCallback(() => {
try { try {
const audioContext = new (window.AudioContext || const audioContext = new (
(window as any).webkitAudioContext)(); window.AudioContext || (window as any).webkitAudioContext
)();
const oscillator = audioContext.createOscillator(); const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain(); const gainNode = audioContext.createGain();
@ -95,8 +96,9 @@ const FloatingChatWidget = () => {
// Play sound for AI responses (Intercom-style) // Play sound for AI responses (Intercom-style)
const playResponseSound = useCallback(() => { const playResponseSound = useCallback(() => {
try { try {
const audioContext = new (window.AudioContext || const audioContext = new (
(window as any).webkitAudioContext)(); window.AudioContext || (window as any).webkitAudioContext
)();
const oscillator = audioContext.createOscillator(); const oscillator = audioContext.createOscillator();
const gainNode = audioContext.createGain(); const gainNode = audioContext.createGain();
@ -266,7 +268,7 @@ const FloatingChatWidget = () => {
// Wait for state to update, then send // Wait for state to update, then send
setTimeout(() => { setTimeout(() => {
handlePressEnter([]); handlePressEnter({ enableThinking: false });
// Clear our local input after sending // Clear our local input after sending
setInputValue(''); setInputValue('');
}, 50); }, 50);

View File

@ -18,11 +18,11 @@ import { cn } from '@/lib/utils';
import { t } from 'i18next'; import { t } from 'i18next';
import { CircleStop, Paperclip, Send, Upload, X } from 'lucide-react'; import { CircleStop, Paperclip, Send, Upload, X } from 'lucide-react';
import * as React from 'react'; import * as React from 'react';
import { useEffect } from 'react'; import { useCallback, useEffect, useState } from 'react';
import { toast } from 'sonner'; import { toast } from 'sonner';
import { AudioButton } from '../ui/audio-button'; import { AudioButton } from '../ui/audio-button';
interface IProps { interface NextMessageInputProps {
disabled: boolean; disabled: boolean;
value: string; value: string;
sendDisabled: boolean; sendDisabled: boolean;
@ -32,14 +32,19 @@ interface IProps {
isShared?: boolean; isShared?: boolean;
showUploadIcon?: boolean; showUploadIcon?: boolean;
isUploading?: boolean; isUploading?: boolean;
onPressEnter(...prams: any[]): void; onPressEnter({ enableThinking }: { enableThinking: boolean }): void;
onInputChange: React.ChangeEventHandler<HTMLTextAreaElement>; onInputChange: React.ChangeEventHandler<HTMLTextAreaElement>;
createConversationBeforeUploadDocument?(message: string): Promise<any>; createConversationBeforeUploadDocument?(message: string): Promise<any>;
stopOutputMessage?(): void; stopOutputMessage?(): void;
onUpload?: NonNullable<FileUploadProps['onUpload']>; onUpload?: NonNullable<FileUploadProps['onUpload']>;
removeFile?(file: File): void; removeFile?(file: File): void;
showReasoning?: boolean;
} }
export type NextMessageInputOnPressEnterParameter = Parameters<
NextMessageInputProps['onPressEnter']
>;
export function NextMessageInput({ export function NextMessageInput({
isUploading = false, isUploading = false,
value, value,
@ -52,12 +57,19 @@ export function NextMessageInput({
stopOutputMessage, stopOutputMessage,
onPressEnter, onPressEnter,
removeFile, removeFile,
}: IProps) { showReasoning = false,
}: NextMessageInputProps) {
const [files, setFiles] = React.useState<File[]>([]); const [files, setFiles] = React.useState<File[]>([]);
const [audioInputValue, setAudioInputValue] = React.useState<string | null>( const [audioInputValue, setAudioInputValue] = React.useState<string | null>(
null, null,
); );
const [enableThinking, setEnableThinking] = useState(false);
const handleThinkingToggle = useCallback(() => {
setEnableThinking((prev) => !prev);
}, []);
useEffect(() => { useEffect(() => {
if (audioInputValue !== null) { if (audioInputValue !== null) {
onInputChange({ onInputChange({
@ -65,11 +77,11 @@ export function NextMessageInput({
} as React.ChangeEvent<HTMLTextAreaElement>); } as React.ChangeEvent<HTMLTextAreaElement>);
setTimeout(() => { setTimeout(() => {
onPressEnter(); onPressEnter({ enableThinking });
setAudioInputValue(null); setAudioInputValue(null);
}, 0); }, 0);
} }
}, [audioInputValue, onInputChange, onPressEnter]); }, [audioInputValue, onInputChange, onPressEnter, enableThinking]);
const onFileReject = React.useCallback((file: File, message: string) => { const onFileReject = React.useCallback((file: File, message: string) => {
toast(message, { toast(message, {
@ -79,9 +91,9 @@ export function NextMessageInput({
const submit = React.useCallback(() => { const submit = React.useCallback(() => {
if (isUploading) return; if (isUploading) return;
onPressEnter(); onPressEnter({ enableThinking });
setFiles([]); setFiles([]);
}, [isUploading, onPressEnter]); }, [isUploading, onPressEnter, enableThinking]);
const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => { const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey) { if (e.key === 'Enter' && !e.shiftKey) {
@ -165,38 +177,49 @@ export function NextMessageInput({
disabled={isUploading || disabled || sendLoading} disabled={isUploading || disabled || sendLoading}
onKeyDown={handleKeyDown} onKeyDown={handleKeyDown}
/> />
<div <div className={cn('flex items-center justify-between gap-1.5')}>
className={cn('flex items-center justify-between gap-1.5', { <div className="flex items-center gap-3">
'justify-end': !showUploadIcon, {showUploadIcon && (
})} <FileUploadTrigger asChild>
> <Button
{showUploadIcon && ( type="button"
<FileUploadTrigger asChild> size="icon"
variant="ghost"
className="size-7 rounded-sm"
disabled={isUploading || sendLoading}
>
<Paperclip className="size-3.5" />
<span className="sr-only">Attach file</span>
</Button>
</FileUploadTrigger>
)}
{showReasoning && (
<Button <Button
type="button" type="button"
size="icon"
variant="ghost" variant="ghost"
className="size-7 rounded-sm" className={cn(
disabled={isUploading || sendLoading} 'rounded-sm h-7 focus-visible:bg-none! hover:bg-none!',
{
'bg-accent-primary text-white': enableThinking,
},
)}
onClick={handleThinkingToggle}
> >
<Paperclip className="size-3.5" /> <span>Thinking</span>
<span className="sr-only">Attach file</span>
</Button> </Button>
</FileUploadTrigger> )}
)} </div>
{sendLoading ? ( {sendLoading ? (
<Button onClick={stopOutputMessage} className="size-5 rounded-sm"> <Button onClick={stopOutputMessage} className="size-5 rounded-sm">
<CircleStop /> <CircleStop />
</Button> </Button>
) : ( ) : (
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
{/* <div className="bg-bg-input rounded-md hover:bg-bg-card p-1"> */}
<AudioButton <AudioButton
onOk={(value) => { onOk={(value) => {
setAudioInputValue(value); setAudioInputValue(value);
}} }}
/> />
{/* </div> */}
<Button <Button
className="size-5 rounded-sm" className="size-5 rounded-sm"
disabled={ disabled={

View File

@ -99,6 +99,7 @@ export interface Message {
files?: (File | UploadResponseDataType)[]; files?: (File | UploadResponseDataType)[];
chatBoxId?: string; chatBoxId?: string;
attachment?: IAttachment; attachment?: IAttachment;
reasoning?: boolean;
} }
export interface IReferenceChunk { export interface IReferenceChunk {

View File

@ -1,3 +1,4 @@
import { NextMessageInputOnPressEnterParameter } from '@/components/message-input/next';
import sonnerMessage from '@/components/ui/message'; import sonnerMessage from '@/components/ui/message';
import { MessageType } from '@/constants/chat'; import { MessageType } from '@/constants/chat';
import { import {
@ -289,6 +290,7 @@ export const useSendAgentMessage = ({
params.files = uploadResponseList; params.files = uploadResponseList;
params.session_id = sessionId; params.session_id = sessionId;
params.reasoning = message.reasoning;
} }
try { try {
@ -355,28 +357,31 @@ export const useSendAgentMessage = ({
removeAllMessagesExceptFirst, removeAllMessagesExceptFirst,
]); ]);
const handlePressEnter = useCallback(() => { const handlePressEnter = useCallback(
if (trim(value) === '') return; (...[{ enableThinking }]: NextMessageInputOnPressEnterParameter) => {
const msgBody = buildRequestBody(value); if (trim(value) === '') return;
if (done) { const msgBody = buildRequestBody(value);
setValue(''); if (done) {
sendMessage({ setValue('');
message: msgBody, sendMessage({
}); message: { ...msgBody, reasoning: enableThinking },
} });
addNewestOneQuestion({ ...msgBody, files: fileList }); }
setTimeout(() => { addNewestOneQuestion({ ...msgBody, files: fileList });
scrollToBottom(); setTimeout(() => {
}, 100); scrollToBottom();
}, [ }, 100);
value, },
done, [
addNewestOneQuestion, value,
fileList, done,
setValue, addNewestOneQuestion,
sendMessage, fileList,
scrollToBottom, setValue,
]); sendMessage,
scrollToBottom,
],
);
const sendedTaskMessage = useRef<boolean>(false); const sendedTaskMessage = useRef<boolean>(false);

View File

@ -164,7 +164,7 @@ const DebugContent = ({
render={({ field }) => ( render={({ field }) => (
<div className="space-y-6"> <div className="space-y-6">
<FormItem className="w-full"> <FormItem className="w-full">
<FormLabel>{t('assistantAvatar')}</FormLabel> <FormLabel>{props.label}</FormLabel>
<FormControl> <FormControl>
<FileUploadDirectUpload <FileUploadDirectUpload
value={field.value} value={field.value}
@ -218,7 +218,7 @@ const DebugContent = ({
BeginQueryTypeMap[BeginQueryType.Paragraph] BeginQueryTypeMap[BeginQueryType.Paragraph]
); );
}, },
[form, t], [form],
); );
const onSubmit = useCallback( const onSubmit = useCallback(

View File

@ -50,11 +50,6 @@ export function ChatPromptEngine() {
tooltip={t('multiTurnTip')} tooltip={t('multiTurnTip')}
></SwitchFormField> ></SwitchFormField>
<UseKnowledgeGraphFormField name="prompt_config.use_kg"></UseKnowledgeGraphFormField> <UseKnowledgeGraphFormField name="prompt_config.use_kg"></UseKnowledgeGraphFormField>
<SwitchFormField
name={'prompt_config.reasoning'}
label={t('reasoning')}
tooltip={t('reasoningTip')}
></SwitchFormField>
<RerankFormFields></RerankFormFields> <RerankFormFields></RerankFormFields>
<CrossLanguageFormField></CrossLanguageFormField> <CrossLanguageFormField></CrossLanguageFormField>
<DynamicVariableForm></DynamicVariableForm> <DynamicVariableForm></DynamicVariableForm>

View File

@ -260,6 +260,7 @@ export function MultipleChatBox({
} }
stopOutputMessage={stopOutputMessage} stopOutputMessage={stopOutputMessage}
onUpload={handleUploadFile} onUpload={handleUploadFile}
showReasoning
/> />
</div> </div>
{visible && ( {visible && (

View File

@ -119,6 +119,7 @@ export function SingleChatBox({
onUpload={handleUploadFile} onUpload={handleUploadFile}
isUploading={isUploading} isUploading={isUploading}
removeFile={removeFile} removeFile={removeFile}
showReasoning
/> />
{visible && ( {visible && (
<PdfSheet <PdfSheet

View File

@ -1,3 +1,4 @@
import { NextMessageInputOnPressEnterParameter } from '@/components/message-input/next';
import { MessageType } from '@/constants/chat'; import { MessageType } from '@/constants/chat';
import { import {
useHandleMessageInputChange, useHandleMessageInputChange,
@ -133,52 +134,56 @@ export const useSendMessage = (controller: AbortController) => {
const { createConversationBeforeSendMessage } = const { createConversationBeforeSendMessage } =
useCreateConversationBeforeSendMessage(); useCreateConversationBeforeSendMessage();
const handlePressEnter = useCallback(async () => { const handlePressEnter = useCallback(
if (trim(value) === '') return; async (...[{ enableThinking }]: NextMessageInputOnPressEnterParameter) => {
if (trim(value) === '') return;
const data = await createConversationBeforeSendMessage(value); const data = await createConversationBeforeSendMessage(value);
if (data === undefined) { if (data === undefined) {
return; return;
} }
const { targetConversationId, currentMessages } = data; const { targetConversationId, currentMessages } = data;
const id = uuid(); const id = uuid();
addNewestQuestion({ addNewestQuestion({
content: value, content: value,
files: files, files: files,
id, id,
role: MessageType.User, role: MessageType.User,
conversationId: targetConversationId, conversationId: targetConversationId,
});
if (done) {
setValue('');
sendMessage({
currentConversationId: targetConversationId,
messages: currentMessages,
message: {
id,
content: value.trim(),
role: MessageType.User,
files: files,
conversationId: targetConversationId,
},
}); });
}
clearFiles(); if (done) {
}, [ setValue('');
value, sendMessage({
createConversationBeforeSendMessage, currentConversationId: targetConversationId,
addNewestQuestion, messages: currentMessages,
files, message: {
done, id,
clearFiles, content: value.trim(),
setValue, role: MessageType.User,
sendMessage, files: files,
]); conversationId: targetConversationId,
reasoning: enableThinking,
},
});
}
clearFiles();
},
[
value,
createConversationBeforeSendMessage,
addNewestQuestion,
files,
done,
clearFiles,
setValue,
sendMessage,
],
);
useEffect(() => { useEffect(() => {
// #1289 // #1289

View File

@ -1,3 +1,4 @@
import { NextMessageInputOnPressEnterParameter } from '@/components/message-input/next';
import showMessage from '@/components/ui/message'; import showMessage from '@/components/ui/message';
import { MessageType } from '@/constants/chat'; import { MessageType } from '@/constants/chat';
import { import {
@ -175,63 +176,67 @@ export function useSendMultipleChatMessage(
], ],
); );
const handlePressEnter = useCallback(async () => { const handlePressEnter = useCallback(
if (trim(value) === '') return; async (...[{ enableThinking }]: NextMessageInputOnPressEnterParameter) => {
const id = uuid(); if (trim(value) === '') return;
const id = uuid();
const data = await createConversationBeforeSendMessage(value); const data = await createConversationBeforeSendMessage(value);
if (data === undefined) { if (data === undefined) {
return; return;
}
const { targetConversationId, currentMessages } = data;
chatBoxIds.forEach((chatBoxId) => {
if (!isLLMConfigEmpty(chatBoxId)) {
addNewestQuestion({
content: value,
id,
role: MessageType.User,
chatBoxId,
files,
conversationId: targetConversationId,
});
} }
});
if (allDone) { const { targetConversationId, currentMessages } = data;
setValue('');
chatBoxIds.forEach((chatBoxId) => { chatBoxIds.forEach((chatBoxId) => {
if (!isLLMConfigEmpty(chatBoxId)) { if (!isLLMConfigEmpty(chatBoxId)) {
sendMessage({ addNewestQuestion({
message: { content: value,
id, id,
content: value.trim(), role: MessageType.User,
role: MessageType.User,
files,
conversationId: targetConversationId,
},
chatBoxId, chatBoxId,
currentConversationId: targetConversationId, files,
messages: currentMessages, conversationId: targetConversationId,
}); });
} }
}); });
}
clearFiles(); if (allDone) {
}, [ setValue('');
value, chatBoxIds.forEach((chatBoxId) => {
createConversationBeforeSendMessage, if (!isLLMConfigEmpty(chatBoxId)) {
chatBoxIds, sendMessage({
allDone, message: {
clearFiles, id,
isLLMConfigEmpty, content: value.trim(),
addNewestQuestion, role: MessageType.User,
files, files,
setValue, conversationId: targetConversationId,
sendMessage, reasoning: enableThinking,
]); },
chatBoxId,
currentConversationId: targetConversationId,
messages: currentMessages,
});
}
});
}
clearFiles();
},
[
value,
createConversationBeforeSendMessage,
chatBoxIds,
allDone,
clearFiles,
isLLMConfigEmpty,
addNewestQuestion,
files,
setValue,
sendMessage,
],
);
useEffect(() => { useEffect(() => {
if (answer.answer && conversationId) { if (answer.answer && conversationId) {

View File

@ -1,3 +1,4 @@
import { NextMessageInputOnPressEnterParameter } from '@/components/message-input/next';
import { MessageType, SharedFrom } from '@/constants/chat'; import { MessageType, SharedFrom } from '@/constants/chat';
import { import {
useHandleMessageInputChange, useHandleMessageInputChange,
@ -24,8 +25,7 @@ export const useGetSharedChatSearchParams = () => {
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const data_prefix = 'data_'; const data_prefix = 'data_';
const data = Object.fromEntries( const data = Object.fromEntries(
searchParams Array.from(searchParams.entries())
.entries()
.filter(([key]) => key.startsWith(data_prefix)) .filter(([key]) => key.startsWith(data_prefix))
.map(([key, value]) => [key.replace(data_prefix, ''), value]), .map(([key, value]) => [key.replace(data_prefix, ''), value]),
); );
@ -72,6 +72,7 @@ export const useSendSharedMessage = () => {
quote: true, quote: true,
question: message.content, question: message.content,
session_id: get(derivedMessages, '0.session_id'), session_id: get(derivedMessages, '0.session_id'),
reasoning: message.reasoning,
}); });
if (isCompletionError(res)) { if (isCompletionError(res)) {
@ -118,14 +119,14 @@ export const useSendSharedMessage = () => {
}, [answer, addNewestAnswer]); }, [answer, addNewestAnswer]);
const handlePressEnter = useCallback( const handlePressEnter = useCallback(
(documentIds: string[]) => { (...[{ enableThinking }]: NextMessageInputOnPressEnterParameter) => {
if (trim(value) === '') return; if (trim(value) === '') return;
const id = uuid(); const id = uuid();
if (done) { if (done) {
setValue(''); setValue('');
addNewestQuestion({ addNewestQuestion({
content: value, content: value,
doc_ids: documentIds, doc_ids: [],
id, id,
role: MessageType.User, role: MessageType.User,
}); });
@ -133,6 +134,7 @@ export const useSendSharedMessage = () => {
content: value.trim(), content: value.trim(),
id, id,
role: MessageType.User, role: MessageType.User,
reasoning: enableThinking,
}); });
} }
}, },

View File

@ -123,6 +123,7 @@ const ChatContainer = () => {
uploadMethod="external_upload_and_parse" uploadMethod="external_upload_and_parse"
showUploadIcon={false} showUploadIcon={false}
stopOutputMessage={stopOutputMessage} stopOutputMessage={stopOutputMessage}
showReasoning
></NextMessageInput> ></NextMessageInput>
</div> </div>
</div> </div>