Skip to content

Commit

Permalink
feat: add stop in chatpage
Browse files Browse the repository at this point in the history
  • Loading branch information
dolphin0618 committed Jun 26, 2024
1 parent cfbad0d commit a2b7217
Show file tree
Hide file tree
Showing 11 changed files with 66 additions and 21 deletions.
2 changes: 1 addition & 1 deletion src/frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,5 @@ To learn React, check out the [React documentation](https://reactjs.org/).

TODO

advance false 是显示在组件中
advance false 显示在组件中
show
1 change: 1 addition & 0 deletions src/frontend/public/locales/en/bs.json
Original file line number Diff line number Diff line change
Expand Up @@ -635,5 +635,6 @@
"endDate": "End Date",
"actionBehavior": "Action Behavior"
},
"chatTipsTitle": "Chat Tips",
"chatTips": "1. Please comply with the Cybersecurity Law of the People's Republic of China, the Data Security Law of the People's Republic of China, the Personal Information Protection Law of the People's Republic of China, and the Basic Requirements for the Security of Generative Artificial Intelligence Services;\n2. It is forbidden to upload confidential data that falls within the scope of the company's confidentiality management regulations;\n3. It is forbidden to upload data containing personal privacy information;\n4. It is forbidden to upload files containing malicious programs or viruses;\n5. It is forbidden to use AI to generate offensive code;\n6. It is forbidden to ask AI questions involving but not limited to explosives, terrorism, pornography, and information that endangers national and public security;\n7. AI-generated content is subject to the company's confidentiality management regulations. Users should judge the reasonableness of the generated content based on the actual situation to avoid risks caused by AI hallucinations."
}
1 change: 1 addition & 0 deletions src/frontend/public/locales/zh/bs.json
Original file line number Diff line number Diff line change
Expand Up @@ -631,5 +631,6 @@
"endDate": "结束日期",
"actionBehavior": "操作行为"
},
"chatTipsTitle": "使用提示",
"chatTips": "1. 请遵守《中华人民共和国网络安全法》《中华人民共和国数据安全法》《中华人民共和国个人信息保护法》及《生成式人工智能服务安全基本要求》;\n2. 禁止上传涉及公司保密管理规定范围内的保密数据;\n3. 禁止上传包含个人隐私信息的数据;\n4. 禁止上传包含恶意程序或病毒的文件;\n5. 禁止使用 AI 生成攻击性代码;\n6. 禁止向 AI 提问包括但不限于涉爆涉恐涉黄及危害国家安全及公共安全的违法不良信息;\n7. AI 生成内容受到公司保密管理规定约束。用户应根据实际情况判断生成内容的合理性,避免 AI 幻觉造成的风险。"
}
16 changes: 11 additions & 5 deletions src/frontend/src/components/Pro/security/FlowSetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { useTranslation } from "react-i18next";
import FormSet from "./FormSet";
import FormView from "./FormView";

export default function FlowSetting({ id, type, isOnline }) {
export default function FlowSetting({ id, type, isOnline, onSubTask }) {
const { t } = useTranslation();

const [open, setOpen] = useState(false);
Expand Down Expand Up @@ -45,21 +45,27 @@ export default function FlowSetting({ id, type, isOnline }) {

setForm(_form);
if (isOnline) return; // 在线状态不允许修改
await sensitiveSaveApi({ ..._form, id, type });
message({ title: t('prompt'), variant: 'success', description: t('build.saveSuccess') });
const callBack = async (id) => {
await sensitiveSaveApi({ ..._form, id, type });
message({ title: t('prompt'), variant: 'success', description: t('build.saveSuccess') });
}
id ? callBack(id) : onSubTask?.(callBack);
};

const onOff = (bln) => {
setForm({ ...form, isCheck: bln });
if (bln) setOpen(true);
if (isOnline) return; // 在线状态不允许修改
sensitiveSaveApi({ ...form, isCheck: bln, id, type });
const callBack = async (id) => {
sensitiveSaveApi({ ...form, isCheck: bln, id, type });
}
id ? callBack(id) : onSubTask?.(callBack);
};

return (
<div>
<div className="mt-6 flex items-center h-[30px] mb-4 px-6">
{/* <span className="text-sm font-medium leading-none">开启内容安全审查</span> */}
{/* <span className="text-sm font-medium leading-none">开启内容安全审查</span> */}
<div className="flex items-center space-x-2">
<span>{t('build.enableContentSecurityReview')}</span>
<TooltipProvider delayDuration={0}>
Expand Down
42 changes: 37 additions & 5 deletions src/frontend/src/components/bs-comp/chatComponent/ChatInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import { useTranslation } from "react-i18next";
import { useMessageStore } from "./messageStore";
import GuideQuestions from "./GuideQuestions";
import { ClearIcon } from "@/components/bs-icons/clear";
import { Button } from "@/components/bs-ui/button";
import { PauseIcon, StopIcon } from "@radix-ui/react-icons";

export default function ChatInput({ clear, form, questions, inputForm, wsUrl, onBeforSend }) {
export default function ChatInput({ clear, form, stop, questions, inputForm, wsUrl, onBeforSend }) {
const { toast } = useToast()
const { t } = useTranslation()
const { appConfig } = useContext(locationContext)
Expand All @@ -21,7 +23,8 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on
const { messages, hisMessages, chatId, createSendMsg, createWsMsg, updateCurrentMessage, destory, setShowGuideQuestion } = useMessageStore()
const currentChatIdRef = useRef(null)
const inputRef = useRef(null)

// 停止状态
const [stoped, setStoped] = useState(true)
/**
* 记录会话切换状态,等待消息加载完成时,控制表单在新会话自动展开
*/
Expand Down Expand Up @@ -98,6 +101,8 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on

const sendWsMsg = async (msg) => {
try {
console.log('WebSocket send: ' + Date.now() + ' 毫秒');

wsRef.current.send(JSON.stringify(msg))
} catch (error) {
toast({
Expand All @@ -117,14 +122,23 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on

return new Promise((res, rej) => {
try {
let startTime = Date.now();
const ws = new WebSocket(`${webSocketProtocol}://${wsUrl}&chat_id=${chatId}`)
wsRef.current = ws
// websocket linsen
ws.onopen = () => {
// 记录连接成功的时间
let endTime = Date.now();

// 计算连接建立所需的时间
let connectionTime = endTime - startTime;

console.log('WebSocket 连接建立时间: ' + connectionTime + ' 毫秒');
console.log("WebSocket connection established!");
res('ok')
};
ws.onmessage = (event) => {
console.log('WebSocket get: ' + Date.now() + ' 毫秒');
const data = JSON.parse(event.data);
const errorMsg = data.category === 'error' ? data.intermediate_steps : ''
// 异常类型处理,提示
Expand All @@ -140,6 +154,8 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on
ws.onclose = (event) => {
wsRef.current = null
console.error('链接手动断开 event :>> ', event);
setStoped(true)

if ([1005, 1008, 1009].includes(event.code)) {
console.warn('即将废弃 :>> ');
setInputLock({ locked: true, reason: event.reason })
Expand All @@ -156,6 +172,7 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on
};
ws.onerror = (ev) => {
wsRef.current = null
setStoped(true)
console.error('链接异常error', ev);
toast({
title: `${t('chat.networkError')}:`,
Expand Down Expand Up @@ -196,12 +213,14 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on
liked: 0
}, data.type === 'end_cover')
} else if (data.type === "close") {
setStoped(true)
setInputLock({ locked: false, reason: '' })
} else if (data.type === 'begin') {
setStoped(false)
}

}

// 监听重发消息事件
// 触发发送消息事件(重试、表单)
useEffect(() => {
const handleCustomEvent = (e) => {
if (!showWhenLocked && inputLock.locked) return console.error('弹窗已锁定,消息无法发送')
Expand Down Expand Up @@ -256,7 +275,7 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on
><ClearIcon className={!showWhenLocked && inputLock.locked ? 'text-gray-400' : 'text-gray-950'} ></ClearIcon></div>
}
</div>
{/* form */}
{/* form switch */}
<div className="flex absolute left-3 top-4 z-10">
{
form && <div
Expand Down Expand Up @@ -290,6 +309,19 @@ export default function ChatInput({ clear, form, questions, inputForm, wsUrl, on
}
}}
></Textarea>
{/* stop */}
{
stop && <div className=" absolute w-full flex justify-center bottom-32">
<Button
className="rounded-full"
variant="outline"
disabled={stoped}
onClick={() => { setStoped(true); sendWsMsg({ "action": "stop" }); }}
>
<PauseIcon className="mr-2" />Stop
</Button>
</div>
}
</div>
<p className="text-center text-sm pt-2 pb-4 text-gray-400">{appConfig.dialogTips}</p>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ export default function MessagePanne({ useName, guideWord, loadMore }) {
type = 'separator'
} else if (msg.files?.length) {
type = 'file'
} else if (['tool', 'flow', 'knowledge'].includes(msg.category)
|| msg.category === 'processing') { // 项目演示?
} else if (['tool', 'flow', 'knowledge'].includes(msg.category)) {
// || msg.category === 'processing') { // 项目演示?
type = 'runLog'
} else if (msg.thought) {
type = 'system'
Expand Down
4 changes: 2 additions & 2 deletions src/frontend/src/components/bs-comp/chatComponent/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import ChatInput from "./ChatInput";
import MessagePanne from "./MessagePanne";

export default function ChatComponent({ clear = false, questions = [], form = false, useName, inputForm = null, guideWord, wsUrl, onBeforSend, loadMore = () => { } }) {
export default function ChatComponent({ stop = false, clear = false, questions = [], form = false, useName, inputForm = null, guideWord, wsUrl, onBeforSend, loadMore = () => { } }) {

return <div className="relative h-full">
<MessagePanne useName={useName} guideWord={guideWord} loadMore={loadMore}></MessagePanne>
<ChatInput clear={clear} questions={questions} form={form} wsUrl={wsUrl} inputForm={inputForm} onBeforSend={onBeforSend} ></ChatInput>
<ChatInput stop={stop} clear={clear} questions={questions} form={form} wsUrl={wsUrl} inputForm={inputForm} onBeforSend={onBeforSend} ></ChatInput>
</div>
};
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ export default function ChatPanne({ customWsHost = '', appendHistory = false, da
</div>
<ChatComponent
form={flowSate.isForm}
// stop={flowSate.isReport || flowSate.isRoom}
useName={sendUserName}
guideWord={flow.guide_word}
wsUrl={wsUrl}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ export default function ForcePrompt({ id }) {
if (!isPrompted) return null;

return (
<div className="absolute top-0 left-0 w-full h-full z-10 bg-[rgba(0,0,0,0.1)] flex items-center justify-center">
<div className="absolute top-0 left-0 w-full h-full z-50 bg-[rgba(0,0,0,0.1)] flex items-center justify-center">
<div className="w-[600px] max-w-[80%] bg-[#fff] shadow-md text-center p-10 rounded-md">
<div className="text-left break-all mb-10">
<p className="text-gray-950 mb-5">{t('chatTipsTitle')}</p>
{t('chatTips').split('\n').map((line, index) => (
<p className="text-md mb-1 text-gray-600" key={index}>{line}</p>
))}
Expand Down
8 changes: 4 additions & 4 deletions src/frontend/src/pages/LoginPage/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -178,10 +178,10 @@ export const LoginPage = () => {
)
}
{/* 中英 */}
<Button
{/* <Button
className='h-[48px] mt-[32px] dark:bg-button'
disabled={isLoading} onClick={handleLogin} >{t('login.loginButton')}</Button>
{/* {
disabled={isLoading} onClick={handleLogin} >{t('login.loginButton')}</Button> */}
{
showLogin ? <>
<div className="text-center">
<a href="javascript:;" className=" text-blue-500 text-sm hover:underline" onClick={() => setShowLogin(false)}>{t('login.noAccountRegister')}</a>
Expand All @@ -198,7 +198,7 @@ export const LoginPage = () => {
className='h-[48px] mt-[32px] dark:bg-button'
disabled={isLoading} onClick={handleRegister} >{t('login.registerButton')}</Button>
</>
} */}
}
{appConfig.hasSSO && <LoginBridge />}
</div>
<div className=" absolute right-[16px] bottom-[16px] flex">
Expand Down
5 changes: 4 additions & 1 deletion src/frontend/src/pages/SkillPage/l2Edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ export default function l2Edit() {


const navigate = useNavigate()
const flowSettingSaveRef = useRef(null)
// 创建新技能
const handleCreateNewSkill = async () => {
const name = nameRef.current.value
Expand All @@ -100,6 +101,8 @@ export default function l2Edit() {
}, user.user_name).then(newFlow => {
setFlow('l2 create flow', newFlow)
navigate("/flow/" + newFlow.id, { replace: true }); // l3
// 创建技能后在保存
flowSettingSaveRef.current?.(newFlow.id)
}))
setLoading(false)
}
Expand Down Expand Up @@ -233,7 +236,7 @@ export default function l2Edit() {
</p>
{/* base form */}
<div className="w-full overflow-hidden transition-all px-1">
<FlowSetting id={id} type={2} isOnline={nextFlow?.status === 2} />
<FlowSetting id={id} type={2} isOnline={nextFlow?.status === 2} onSubTask={(fn) => flowSettingSaveRef.current = fn} />
</div>
</div>}
</div>
Expand Down

0 comments on commit a2b7217

Please sign in to comment.