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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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