chat.tsx 81 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470
  1. "use client";
  2. import { useDebouncedCallback } from "use-debounce";
  3. import React, {
  4. useState,
  5. useRef,
  6. useEffect,
  7. useMemo,
  8. useCallback,
  9. Fragment,
  10. RefObject,
  11. } from "react";
  12. import { HomeOutlined, MenuOutlined, MessageOutlined, CopyOutlined, ArrowUpOutlined, AudioOutlined, PauseCircleOutlined, DeleteOutlined } from '@ant-design/icons';
  13. import SendWhiteIcon from "../icons/send-white.svg";
  14. import BrainIcon from "../icons/brain.svg";
  15. import RenameIcon from "../icons/rename.svg";
  16. import ExportIcon from "../icons/share.svg";
  17. import ReturnIcon from "../icons/return.svg";
  18. import CopyIcon from "../icons/copy.svg";
  19. import faviconSrc from "../icons/favicon.png";
  20. import LeftIcon from "../icons/left.svg";
  21. import Favicon from "../icons/favicon.svg";
  22. import LoadingIcon from "../icons/three-dots.svg";
  23. import LoadingButtonIcon from "../icons/loading.svg";
  24. import PromptIcon from "../icons/prompt.svg";
  25. import MaskIcon from "../icons/mask.svg";
  26. import MaxIcon from "../icons/max.svg";
  27. import MinIcon from "../icons/min.svg";
  28. import ResetIcon from "../icons/reload.svg";
  29. import BreakIcon from "../icons/break.svg";
  30. import SettingsIcon from "../icons/chat-settings.svg";
  31. import DeleteIcon from "../icons/clear.svg";
  32. import PinIcon from "../icons/pin.svg";
  33. import EditIcon from "../icons/rename.svg";
  34. import ConfirmIcon from "../icons/confirm.svg";
  35. import CancelIcon from "../icons/cancel.svg";
  36. import ImageIcon from "../icons/image.svg";
  37. import LightIcon from "../icons/light.svg";
  38. import DarkIcon from "../icons/dark.svg";
  39. import AutoIcon from "../icons/auto.svg";
  40. import BottomIcon from "../icons/bottom.svg";
  41. import StopIcon from "../icons/pause.svg";
  42. import RobotIcon from "../icons/robot.svg";
  43. import AddIcon from "../icons/add.svg";
  44. import SizeIcon from "../icons/size.svg";
  45. import PluginIcon from "../icons/plugin.svg";
  46. import avatarSrc from "../icons/avatar.png";
  47. import hlw_selected from "../icons/hlw_selected.png";
  48. import hlw from "../icons/hlw.png";
  49. import tubing from "../icons/tubing.png";
  50. import ffq from "../icons/ffq.png";
  51. import rfq from "../icons/rfq.png";
  52. import {
  53. ChatMessage,
  54. SubmitKey,
  55. useChatStore,
  56. BOT_HELLO,
  57. createMessage,
  58. useAccessStore,
  59. Theme,
  60. useAppConfig,
  61. DEFAULT_TOPIC,
  62. ModelType,
  63. } from "../store";
  64. import {
  65. copyToClipboard,
  66. selectOrCopy,
  67. autoGrowTextArea,
  68. useMobileScreen,
  69. getMessageTextContent,
  70. getMessageImages,
  71. isVisionModel,
  72. isDalle3,
  73. } from "../utils";
  74. import { uploadImage as uploadImageRemote } from "@/app/utils/chat";
  75. import dynamic from "next/dynamic";
  76. import MarkdownIt from 'markdown-it';
  77. import { ChatControllerPool } from "../client/controller";
  78. import { DalleSize } from "../typing";
  79. import { Prompt, usePromptStore } from "../store/prompt";
  80. import { useGlobalStore } from "../store";
  81. import Locale from "../locales";
  82. import { IconButton } from "./button";
  83. import styles from "./chat.module.scss";
  84. import {
  85. List,
  86. ListItem,
  87. Modal,
  88. Selector,
  89. showConfirm,
  90. showPrompt,
  91. showToast,
  92. } from "./ui-lib";
  93. import { useNavigate, useLocation } from "react-router-dom";
  94. import {
  95. CHAT_PAGE_SIZE,
  96. LAST_INPUT_KEY,
  97. Path,
  98. REQUEST_TIMEOUT_MS,
  99. UNFINISHED_INPUT,
  100. ServiceProvider,
  101. Plugin,
  102. } from "../constant";
  103. // Avatar组件替代实现
  104. import BotIcon from "../icons/bot.svg";
  105. import BlackBotIcon from "../icons/black-bot.svg";
  106. // import avatar from "../icons/avatar.png";
  107. import { Typography, Image, Tooltip, Tag } from "antd";
  108. const marked = new MarkdownIt({ html: true, typographer: true });
  109. function Avatar(props: { model?: string; avatar?: string }) {
  110. if (props.model) {
  111. return (
  112. <div className="no-dark">
  113. {props.model?.startsWith("gpt-4") ? (
  114. <BlackBotIcon className="user-avatar" />
  115. ) : (
  116. <img src={avatarSrc.src} className="user-avatar" />
  117. // <BotIcon className="user-avatar" />
  118. )}
  119. </div>
  120. );
  121. }
  122. return (
  123. <div className="user-avatar">
  124. {/* 移除emoji头像,使用默认bot图标 */}
  125. <img src={avatarSrc.src} className="user-avatar" />
  126. </div>
  127. );
  128. }
  129. import { ContextPrompts, MaskAvatar, MaskConfig } from "./mask";
  130. import { useMaskStore } from "../store/mask";
  131. import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
  132. import { prettyObject } from "../utils/format";
  133. import { ExportMessageModal } from "./exporter";
  134. import { getClientConfig } from "../config/client";
  135. import { useAllModels } from "../utils/hooks";
  136. import { Button, Collapse, Drawer, message, Popover, Select, Skeleton, Space } from 'antd';
  137. import {
  138. FileOutlined,
  139. FilePdfOutlined,
  140. FileTextOutlined,
  141. FileWordOutlined
  142. } from '@ant-design/icons';
  143. import { RightOutlined, CheckCircleOutlined, CaretRightOutlined, StarTwoTone } from '@ant-design/icons';
  144. import api from "@/app/api/api";
  145. import { UserOut } from "../common/user";
  146. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  147. loading: () => <LoadingIcon />,
  148. });
  149. export function SessionConfigModel(props: { onClose: () => void }) {
  150. const chatStore = useChatStore();
  151. const session = chatStore.currentSession();
  152. const maskStore = useMaskStore();
  153. const navigate = useNavigate();
  154. return (
  155. <div className="modal-mask">
  156. <Modal
  157. title={Locale.Context.Edit}
  158. onClose={() => props.onClose()}
  159. actions={[
  160. <IconButton
  161. key="reset"
  162. icon={<ResetIcon />}
  163. bordered
  164. text={Locale.Chat.Config.Reset}
  165. onClick={async () => {
  166. if (await showConfirm(Locale.Memory.ResetConfirm)) {
  167. chatStore.updateCurrentSession(
  168. (session) => (session.memoryPrompt = ""),
  169. );
  170. }
  171. }}
  172. />,
  173. <IconButton
  174. key="copy"
  175. icon={<CopyIcon />}
  176. bordered
  177. text={Locale.Chat.Config.SaveAs}
  178. onClick={() => {
  179. navigate(Path.Masks);
  180. setTimeout(() => {
  181. maskStore.create(session.mask);
  182. }, 500);
  183. }}
  184. />,
  185. ]}
  186. >
  187. <MaskConfig
  188. mask={session.mask}
  189. updateMask={(updater) => {
  190. const mask = { ...session.mask };
  191. updater(mask);
  192. chatStore.updateCurrentSession((session) => (session.mask = mask));
  193. }}
  194. shouldSyncFromGlobal
  195. extraListItems={
  196. session.mask.modelConfig.sendMemory ? (
  197. <ListItem
  198. className="copyable"
  199. title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
  200. subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
  201. ></ListItem>
  202. ) : (
  203. <></>
  204. )
  205. }
  206. ></MaskConfig>
  207. </Modal>
  208. </div>
  209. );
  210. }
  211. // 提示词
  212. const CallWord = (props: {
  213. setUserInput: (value: string) => void,
  214. doSubmit: (userInput: string) => void,
  215. }) => {
  216. const { setUserInput, doSubmit } = props
  217. const list = [
  218. {
  219. title: '信息公布',
  220. // text: '在哪里查看招聘信息?',
  221. text: '今年盈科工程咨询的校园招聘什么时候开始?如何查阅相关招聘信息?',
  222. },
  223. {
  224. title: '招聘岗位',
  225. // text: '今年招聘的岗位有哪些?',
  226. text: '今年招聘的岗位有哪些?',
  227. },
  228. {
  229. title: '专业要求',
  230. // text: '招聘的岗位有什么专业要求?',
  231. text: '招聘的岗位有什么专业要求?',
  232. },
  233. {
  234. title: '工作地点',
  235. // text: '全国都有工作地点吗?',
  236. text: '工作地点是如何确定的?',
  237. },
  238. {
  239. title: '薪资待遇',
  240. // text: '企业可提供的薪资与福利待遇如何?',
  241. text: '企业可提供的薪资与福利待遇如何?',
  242. },
  243. {
  244. title: '职业发展',
  245. // text: '我应聘贵单位,你们能提供怎样的职业发展规划?',
  246. text: '公司有哪些职业发展通道?',
  247. },
  248. {
  249. title: '落户政策',
  250. // text: '公司是否能协助我落户?',
  251. text: '关于落户支持?',
  252. }
  253. ]
  254. return (
  255. <>
  256. {
  257. list.map((item, index) => {
  258. return <span
  259. key={index}
  260. style={{
  261. padding: '5px 10px',
  262. background: '#f6f7f8',
  263. color: '#5e5e66',
  264. borderRadius: 4,
  265. margin: '0 5px 10px 0',
  266. cursor: 'pointer',
  267. fontSize: 12
  268. }}
  269. onClick={() => {
  270. const plan: string = '2';
  271. if (plan === '1') {
  272. // 方案1.点击后出现在输入框内,用户自己点击发送
  273. setUserInput(item.text);
  274. } else {
  275. // 方案2.点击后直接发送
  276. doSubmit(item.text)
  277. }
  278. }}
  279. >
  280. {item.title}
  281. </span>
  282. })
  283. }
  284. </>
  285. )
  286. }
  287. function useSubmitHandler() {
  288. const config = useAppConfig();
  289. const submitKey = config.submitKey;
  290. const isComposing = useRef(false);
  291. useEffect(() => {
  292. const onCompositionStart = () => {
  293. isComposing.current = true;
  294. };
  295. const onCompositionEnd = () => {
  296. isComposing.current = false;
  297. };
  298. window.addEventListener("compositionstart", onCompositionStart);
  299. window.addEventListener("compositionend", onCompositionEnd);
  300. return () => {
  301. window.removeEventListener("compositionstart", onCompositionStart);
  302. window.removeEventListener("compositionend", onCompositionEnd);
  303. };
  304. }, []);
  305. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  306. // Fix Chinese input method "Enter" on Safari
  307. if (e.keyCode == 229) return false;
  308. if (e.key !== "Enter") return false;
  309. if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current))
  310. return false;
  311. return (
  312. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  313. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  314. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  315. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  316. (config.submitKey === SubmitKey.Enter &&
  317. !e.altKey &&
  318. !e.ctrlKey &&
  319. !e.shiftKey &&
  320. !e.metaKey)
  321. );
  322. };
  323. return {
  324. submitKey,
  325. shouldSubmit,
  326. };
  327. }
  328. export type RenderPrompt = Pick<Prompt, "title" | "content">;
  329. export function PromptHints(props: {
  330. prompts: RenderPrompt[];
  331. onPromptSelect: (prompt: RenderPrompt) => void;
  332. }) {
  333. const noPrompts = props.prompts.length === 0;
  334. const [selectIndex, setSelectIndex] = useState(0);
  335. const selectedRef = useRef<HTMLDivElement>(null);
  336. useEffect(() => {
  337. setSelectIndex(0);
  338. }, [props.prompts.length]);
  339. useEffect(() => {
  340. const onKeyDown = (e: KeyboardEvent) => {
  341. if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) {
  342. return;
  343. }
  344. // arrow up / down to select prompt
  345. const changeIndex = (delta: number) => {
  346. e.stopPropagation();
  347. e.preventDefault();
  348. const nextIndex = Math.max(
  349. 0,
  350. Math.min(props.prompts.length - 1, selectIndex + delta),
  351. );
  352. setSelectIndex(nextIndex);
  353. selectedRef.current?.scrollIntoView({
  354. block: "center",
  355. });
  356. };
  357. if (e.key === "ArrowUp") {
  358. changeIndex(1);
  359. } else if (e.key === "ArrowDown") {
  360. changeIndex(-1);
  361. } else if (e.key === "Enter") {
  362. const selectedPrompt = props.prompts.at(selectIndex);
  363. if (selectedPrompt) {
  364. props.onPromptSelect(selectedPrompt);
  365. }
  366. }
  367. };
  368. window.addEventListener("keydown", onKeyDown);
  369. return () => window.removeEventListener("keydown", onKeyDown);
  370. // eslint-disable-next-line react-hooks/exhaustive-deps
  371. }, [props.prompts.length, selectIndex]);
  372. if (noPrompts) return null;
  373. return (
  374. <div className={styles["prompt-hints"]}>
  375. {props.prompts.map((prompt, i) => (
  376. <div
  377. ref={i === selectIndex ? selectedRef : null}
  378. className={
  379. styles["prompt-hint"] +
  380. ` ${i === selectIndex ? styles["prompt-hint-selected"] : ""}`
  381. }
  382. key={prompt.title + i.toString()}
  383. onClick={() => props.onPromptSelect(prompt)}
  384. onMouseEnter={() => setSelectIndex(i)}
  385. >
  386. <div className={styles["hint-title"]}>{prompt.title}</div>
  387. <div className={styles["hint-content"]}>{prompt.content}</div>
  388. </div>
  389. ))}
  390. </div>
  391. );
  392. }
  393. function ClearContextDivider() {
  394. const chatStore = useChatStore();
  395. return (
  396. <div
  397. className={styles["clear-context"]}
  398. onClick={() =>
  399. chatStore.updateCurrentSession(
  400. (session) => (session.clearContextIndex = undefined),
  401. )
  402. }
  403. >
  404. <div className={styles["clear-context-tips"]}>{Locale.Context.Clear}</div>
  405. <div className={styles["clear-context-revert-btn"]}>
  406. {Locale.Context.Revert}
  407. </div>
  408. </div>
  409. );
  410. }
  411. // SpeechButton: uses Web Speech API to capture speech and return transcript via onResult
  412. function SpeechButton(props: { onResult: (text: string) => void }) {
  413. const [listening, setListening] = useState(false);
  414. const recognitionRef = useRef<any>(null);
  415. useEffect(() => {
  416. const AnySpeech: any = (window as any).webkitSpeechRecognition || (window as any).SpeechRecognition;
  417. if (!AnySpeech) return;
  418. const recog = new AnySpeech();
  419. recog.continuous = false;
  420. recog.interimResults = false;
  421. recog.lang = 'zh-CN';
  422. recognitionRef.current = recog;
  423. // do not call stop() here — only start/stop on user action
  424. const isRunningRef = { current: false } as { current: boolean };
  425. recog.onstart = () => {
  426. isRunningRef.current = true;
  427. setListening(true);
  428. };
  429. const onresult = (e: any) => {
  430. try {
  431. const transcript = Array.from(e.results)
  432. .map((r: any) => r[0].transcript)
  433. .join('');
  434. if (transcript && props.onResult) props.onResult(transcript.trim());
  435. } catch (err) {
  436. console.error('speech onresult', err);
  437. }
  438. };
  439. const onend = () => {
  440. setListening(false);
  441. };
  442. recog.onresult = onresult;
  443. recog.onend = onend;
  444. return () => {
  445. try {
  446. recog.onresult = null;
  447. recog.onend = null;
  448. recog.onstart = null;
  449. recog.onresult = null;
  450. recog.onend = null;
  451. try {
  452. recog.stop && recog.stop();
  453. } catch (e) {
  454. // ignore stop errors during cleanup
  455. }
  456. } catch (e) {
  457. // ignore
  458. }
  459. };
  460. }, []);
  461. const start = () => {
  462. const recog = recognitionRef.current;
  463. if (!recog) {
  464. showToast('当前浏览器不支持语音识别');
  465. return;
  466. }
  467. try {
  468. // prevent double start which causes InvalidStateError
  469. // some browsers throw if start is called while recognition already running
  470. if ((recog as any).running) {
  471. return;
  472. }
  473. recog.start();
  474. } catch (e) {
  475. console.error('start recog', e);
  476. // provide friendly message for common invalid state
  477. if ((e as any).name === 'InvalidStateError') {
  478. showToast('语音识别已在运行中');
  479. }
  480. }
  481. };
  482. const stop = () => {
  483. const recog = recognitionRef.current;
  484. try {
  485. // stop only if available and running
  486. try {
  487. recog.stop && recog.stop();
  488. } catch (e) {
  489. console.warn('stop recog error', e);
  490. }
  491. } catch (e) {
  492. // ignore
  493. }
  494. setListening(false);
  495. };
  496. return (
  497. <Button
  498. className={styles['speech-button']}
  499. onClick={() => (listening ? stop() : start())}
  500. title={listening ? '点击停止语音输入' : '点击开始语音输入'}
  501. type="primary"
  502. >
  503. {listening ? <PauseCircleOutlined style={{ fontSize: 18 }} /> : <AudioOutlined style={{ fontSize: 18 }} />}
  504. </Button>
  505. );
  506. }
  507. export function ChatAction(props: {
  508. text: string;
  509. icon: JSX.Element;
  510. onClick: () => void;
  511. }) {
  512. const iconRef = useRef<HTMLDivElement>(null);
  513. const textRef = useRef<HTMLDivElement>(null);
  514. const [width, setWidth] = useState({
  515. full: 16,
  516. icon: 16,
  517. });
  518. function updateWidth() {
  519. if (!iconRef.current || !textRef.current) return;
  520. const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width;
  521. const textWidth = getWidth(textRef.current);
  522. const iconWidth = getWidth(iconRef.current);
  523. setWidth({
  524. full: textWidth + iconWidth,
  525. icon: iconWidth,
  526. });
  527. }
  528. return (
  529. <div
  530. className={`${styles["chat-input-action"]} clickable`}
  531. onClick={() => {
  532. props.onClick();
  533. setTimeout(updateWidth, 1);
  534. }}
  535. onMouseEnter={updateWidth}
  536. onTouchStart={updateWidth}
  537. style={
  538. {
  539. "--icon-width": `${width.icon}px`,
  540. "--full-width": `${width.full}px`,
  541. } as React.CSSProperties
  542. }
  543. >
  544. <div ref={iconRef} className={styles["icon"]}>
  545. {props.icon}
  546. </div>
  547. <div className={styles["text"]} ref={textRef}>
  548. {props.text}
  549. </div>
  550. </div>
  551. );
  552. }
  553. function useScrollToBottom(
  554. scrollRef: RefObject<HTMLDivElement>,
  555. detach: boolean = false,
  556. ) {
  557. // for auto-scroll
  558. const [autoScroll, setAutoScroll] = useState(true);
  559. function scrollDomToBottom() {
  560. const dom = scrollRef.current;
  561. if (dom) {
  562. requestAnimationFrame(() => {
  563. setAutoScroll(true);
  564. dom.scrollTo(0, dom.scrollHeight);
  565. });
  566. }
  567. }
  568. // auto scroll
  569. useEffect(() => {
  570. if (autoScroll && !detach) {
  571. scrollDomToBottom();
  572. }
  573. });
  574. return {
  575. scrollRef,
  576. autoScroll,
  577. setAutoScroll,
  578. scrollDomToBottom,
  579. };
  580. }
  581. export function ChatActions(props: {
  582. isClickStop: boolean,
  583. sendStatus: boolean,
  584. setSendStatus: (status: boolean) => void;
  585. setUserInput: (value: string) => void;
  586. doSubmit: (userInput: string) => void;
  587. uploadImage: () => void;
  588. setAttachImages: (images: string[]) => void;
  589. setUploading: (uploading: boolean) => void;
  590. showPromptModal: () => void;
  591. scrollToBottom: () => void;
  592. showPromptHints: () => void;
  593. hitBottom: boolean;
  594. uploading: boolean;
  595. }) {
  596. const config = useAppConfig();
  597. const navigate = useNavigate();
  598. const chatStore = useChatStore();
  599. // switch themes
  600. const theme = config.theme;
  601. function nextTheme() {
  602. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  603. const themeIndex = themes.indexOf(theme);
  604. const nextIndex = (themeIndex + 1) % themes.length;
  605. const nextTheme = themes[nextIndex];
  606. config.update((config) => (config.theme = nextTheme));
  607. }
  608. // stop all responses
  609. const couldStop = ChatControllerPool.hasPending();
  610. const stopAll = () => ChatControllerPool.stopAll();
  611. // switch model
  612. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  613. const currentProviderName =
  614. chatStore.currentSession().mask.modelConfig?.providerName ||
  615. ServiceProvider.OpenAI;
  616. const allModels = useAllModels();
  617. const models = useMemo(() => {
  618. const filteredModels = allModels.filter((m) => m.available);
  619. const defaultModel = filteredModels.find((m) => m.isDefault);
  620. if (defaultModel) {
  621. const arr = [
  622. defaultModel,
  623. ...filteredModels.filter((m) => m !== defaultModel),
  624. ];
  625. return arr;
  626. } else {
  627. return filteredModels;
  628. }
  629. }, [allModels]);
  630. const currentModelName = useMemo(() => {
  631. const model = models.find(
  632. (m) =>
  633. m.name == currentModel &&
  634. m?.provider?.providerName == currentProviderName,
  635. );
  636. return model?.displayName ?? "";
  637. }, [models, currentModel, currentProviderName]);
  638. const [showModelSelector, setShowModelSelector] = useState(false);
  639. const [showPluginSelector, setShowPluginSelector] = useState(false);
  640. const [showUploadImage, setShowUploadImage] = useState(false);
  641. type GuessList = string[]
  642. const [guessList, setGuessList] = useState<GuessList>([]);
  643. const [showSizeSelector, setShowSizeSelector] = useState(false);
  644. const dalle3Sizes: DalleSize[] = ["1024x1024", "1792x1024", "1024x1792"];
  645. const currentSize =
  646. chatStore.currentSession().mask.modelConfig?.size ?? "1024x1024";
  647. const session = chatStore.currentSession();
  648. useEffect(() => {
  649. const show = isVisionModel(currentModel);
  650. setShowUploadImage(show);
  651. if (!show) {
  652. props.setAttachImages([]);
  653. props.setUploading(false);
  654. }
  655. // if current model is not available
  656. // switch to first available model
  657. const isUnavaliableModel = !models.some((m) => m.name === currentModel);
  658. if (isUnavaliableModel && models.length > 0) {
  659. // show next model to default model if exist
  660. let nextModel = models.find((model) => model.isDefault) || models[0];
  661. chatStore.updateCurrentSession((session) => {
  662. session.mask.modelConfig.model = nextModel.name;
  663. session.mask.modelConfig.providerName = nextModel?.provider?.providerName as ServiceProvider;
  664. });
  665. showToast(
  666. nextModel?.provider?.providerName == "ByteDance"
  667. ? nextModel.displayName
  668. : nextModel.name,
  669. );
  670. }
  671. }, [chatStore, currentModel, models]);
  672. const fetchGuessList = async (record: { content: string; role: string }) => {
  673. try {
  674. const data = {
  675. appId: session.appId,
  676. messages: [
  677. {
  678. content: btoa(unescape(encodeURIComponent(record.content))),
  679. role: record.role,
  680. }
  681. ],
  682. chat_id: session.chat_id,
  683. }
  684. let url = '/deepseek/api/async/completions';
  685. const res = await api.post(url, data);
  686. setGuessList(res.data);
  687. } catch (error) {
  688. console.error(error);
  689. }
  690. }
  691. useEffect(() => {
  692. setGuessList([]);
  693. if (chatStore.message.content) {
  694. fetchGuessList(chatStore.message);
  695. }
  696. }, [chatStore.message]);
  697. useEffect(() => {
  698. if (props.isClickStop) {
  699. props.setSendStatus(false);
  700. setGuessList([]);
  701. }
  702. }, [props.isClickStop])
  703. const [activeKey, setActiveKey] = useState('0'); // 控制手风琴是否展示
  704. return (
  705. <div className={styles["chat-input-actions"]}>
  706. {
  707. props.sendStatus &&
  708. <Collapse
  709. accordion={true}
  710. activeKey={activeKey}
  711. onChange={(key) => { setActiveKey(key[0]) }}
  712. bordered={false}
  713. style={{ width: '100%', backgroundColor: '#fff' }}
  714. expandIconPosition="end"
  715. items={[
  716. {
  717. key: '1',
  718. label: <span style={{ color: '#8096ca' }}>你还可以尝试提问:</span>,
  719. children: <div style={{ color: '#8096ca', fontSize: 13, overflowX: 'auto' }}>
  720. {/* <div>
  721. 你还可以尝试提问:
  722. </div> */}
  723. {
  724. guessList.length === 0 ?
  725. <Space style={{ margin: '10px 0' }}>
  726. <Skeleton.Button size="small" active={true} />
  727. <Skeleton.Button size="small" active={true} />
  728. <Skeleton.Button size="small" active={true} />
  729. </Space>
  730. :
  731. <div style={{ display: 'flex', margin: '10px 0', overflowX: 'auto' }}>
  732. {
  733. guessList.map((item, index) => {
  734. return (
  735. <div
  736. style={{
  737. padding: '5px 10px',
  738. background: '#f2f4f8',
  739. borderRadius: 5,
  740. margin: '0 10px 10px 0',
  741. cursor: 'pointer',
  742. }}
  743. onClick={() => {
  744. props.setUserInput(item);
  745. props.doSubmit(item)
  746. setActiveKey('')
  747. }}
  748. key={index}
  749. >
  750. {item}
  751. </div>
  752. )
  753. })
  754. }
  755. </div>
  756. }
  757. </div>
  758. }
  759. ]}
  760. />
  761. }
  762. {showModelSelector && (
  763. <Selector
  764. defaultSelectedValue={`${currentModel}@${currentProviderName}`}
  765. items={models.map((m) => ({
  766. title: `${m.displayName}${m?.provider?.providerName
  767. ? "(" + m?.provider?.providerName + ")"
  768. : ""
  769. }`,
  770. value: `${m.name}@${m?.provider?.providerName}`,
  771. }))}
  772. onClose={() => setShowModelSelector(false)}
  773. onSelection={(s) => {
  774. if (s.length === 0) return;
  775. const [model, providerName] = s[0].split("@");
  776. chatStore.updateCurrentSession((session) => {
  777. session.mask.modelConfig.model = model as ModelType;
  778. session.mask.modelConfig.providerName =
  779. providerName as ServiceProvider;
  780. session.mask.syncGlobalConfig = false;
  781. });
  782. if (providerName == "ByteDance") {
  783. const selectedModel = models.find(
  784. (m) =>
  785. m.name == model && m?.provider?.providerName == providerName,
  786. );
  787. showToast(selectedModel?.displayName ?? "");
  788. } else {
  789. showToast(model);
  790. }
  791. }}
  792. />
  793. )}
  794. {isDalle3(currentModel) && (
  795. <ChatAction
  796. onClick={() => setShowSizeSelector(true)}
  797. text={currentSize}
  798. icon={<SizeIcon />}
  799. />
  800. )}
  801. {showSizeSelector && (
  802. <Selector
  803. defaultSelectedValue={currentSize}
  804. items={dalle3Sizes.map((m) => ({
  805. title: m,
  806. value: m,
  807. }))}
  808. onClose={() => setShowSizeSelector(false)}
  809. onSelection={(s) => {
  810. if (s.length === 0) return;
  811. const size = s[0];
  812. chatStore.updateCurrentSession((session) => {
  813. session.mask.modelConfig.size = size;
  814. });
  815. showToast(size);
  816. }}
  817. />
  818. )}
  819. {/* <ChatAction
  820. onClick={() => setShowPluginSelector(true)}
  821. text={Locale.Plugin.Name}
  822. icon={<PluginIcon />}
  823. /> */}
  824. {showPluginSelector && (
  825. <Selector
  826. multiple
  827. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  828. items={[
  829. {
  830. title: Locale.Plugin.Artifacts,
  831. value: Plugin.Artifacts,
  832. },
  833. ]}
  834. onClose={() => setShowPluginSelector(false)}
  835. onSelection={(s) => {
  836. const plugin = s[0];
  837. chatStore.updateCurrentSession((session) => {
  838. session.mask.plugin = s;
  839. });
  840. if (plugin) {
  841. showToast(plugin);
  842. }
  843. }}
  844. />
  845. )}
  846. </div>
  847. );
  848. }
  849. export function EditMessageModal(props: { onClose: () => void }) {
  850. const chatStore = useChatStore();
  851. const session = chatStore.currentSession();
  852. const [messages, setMessages] = useState(session.messages.slice());
  853. return (
  854. <div className="modal-mask">
  855. <Modal
  856. title={Locale.Chat.EditMessage.Title}
  857. onClose={props.onClose}
  858. actions={[
  859. <IconButton
  860. text={Locale.UI.Cancel}
  861. icon={<CancelIcon />}
  862. key="cancel"
  863. onClick={() => {
  864. props.onClose();
  865. }}
  866. />,
  867. <IconButton
  868. type="primary"
  869. text={Locale.UI.Confirm}
  870. icon={<ConfirmIcon />}
  871. key="ok"
  872. onClick={() => {
  873. chatStore.updateCurrentSession(
  874. (session) => (session.messages = messages),
  875. );
  876. props.onClose();
  877. }}
  878. />,
  879. ]}
  880. >
  881. <List>
  882. <ListItem
  883. title={Locale.Chat.EditMessage.Topic.Title}
  884. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  885. >
  886. <input
  887. type="text"
  888. value={session.topic}
  889. onInput={(e) =>
  890. chatStore.updateCurrentSession(
  891. (session) => (session.topic = e.currentTarget.value),
  892. )
  893. }
  894. ></input>
  895. </ListItem>
  896. </List>
  897. <ContextPrompts
  898. context={messages}
  899. updateContext={(updater) => {
  900. const newMessages = messages.slice();
  901. updater(newMessages);
  902. setMessages(newMessages);
  903. }}
  904. />
  905. </Modal>
  906. </div>
  907. );
  908. }
  909. export function DeleteImageButton(props: { deleteImage: () => void }) {
  910. return (
  911. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  912. <DeleteIcon />
  913. </div>
  914. );
  915. }
  916. function _Chat() {
  917. type RenderMessage = ChatMessage & { preview?: boolean };
  918. const chatStore = useChatStore();
  919. const session = chatStore.currentSession();
  920. const config = useAppConfig();
  921. config.sendPreviewBubble = false;
  922. const fontSize = config.fontSize;
  923. const fontFamily = config.fontFamily;
  924. const [showExport, setShowExport] = useState(false);
  925. const inputRef = useRef<HTMLTextAreaElement>(null);
  926. const [userInput, setUserInput] = useState("");
  927. const [isLoading, setIsLoading] = useState(false);
  928. const [sendStatus, setSendStatus] = useState(false);
  929. const { submitKey, shouldSubmit } = useSubmitHandler();
  930. const scrollRef = useRef<HTMLDivElement>(null);
  931. const isScrolledToBottom = scrollRef?.current
  932. ? Math.abs(
  933. scrollRef.current.scrollHeight -
  934. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  935. ) <= 1
  936. : false;
  937. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  938. scrollRef,
  939. isScrolledToBottom,
  940. );
  941. const [hitBottom, setHitBottom] = useState(true);
  942. const isMobileScreen = useMobileScreen();
  943. const navigate = useNavigate();
  944. const [attachImages, setAttachImages] = useState<string[]>([]);
  945. const [uploading, setUploading] = useState(false);
  946. // prompt hints
  947. const promptStore = usePromptStore();
  948. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  949. const onSearch = useDebouncedCallback(
  950. (text: string) => {
  951. const matchedPrompts = promptStore.search(text);
  952. setPromptHints(matchedPrompts);
  953. },
  954. 100,
  955. { leading: true, trailing: true },
  956. );
  957. type AppList = {
  958. label: string,
  959. value: string,
  960. desc: string,
  961. }[];
  962. const [appList, setAppList] = useState<AppList>([]);
  963. const [appValue, setAppValue] = useState<string>();
  964. const globalStore = useGlobalStore();
  965. type QuestionList = { question: string, questionIndex: number, id: string, appId: string, createTime: string }[];
  966. const [questionList, setQuestionList] = useState<QuestionList>([]);// 预设问题列表
  967. const [detail, setDetail] = useState<any>(null);// 应用详情
  968. const location = useLocation();
  969. const [loading, setLoading] = useState<boolean>(false);
  970. const fruits = [
  971. { id: 'LOCAL', name: 'deepseek' },
  972. { id: 'ONLINE', name: '智谱AI' },
  973. ];
  974. const [selectedFruit, setSelectedFruit] = React.useState(chatStore.chatMode);
  975. // 获取应用详情
  976. const fetchApplicationDetail = async (appId: any) => {
  977. if (!appId) return
  978. setLoading(true);
  979. try {
  980. let url = `/deepseek/api/selectApplication/${appId}`;
  981. const res: any = await api.get(url);
  982. if (res.code === 200) {
  983. setDetail(res.data?.detail);
  984. setQuestionList(res.data?.questionlist || []);
  985. } else {
  986. message.error(res.message || '应用详情获取失败');
  987. }
  988. return
  989. } catch (error) {
  990. console.error(error);
  991. } finally {
  992. setLoading(false);
  993. }
  994. }
  995. const InitChat = async (appId: any) => {
  996. await fetchApplicationDetail(appId);
  997. }
  998. useEffect(() => {
  999. const search = location.search;
  1000. const params = new URLSearchParams(search);
  1001. const chatMode = params.get('chatMode') || 'LOCAL';
  1002. if (chatMode) {
  1003. setSelectedFruit(chatMode as "ONLINE" | "LOCAL");
  1004. let appId = params.get('appId');
  1005. console.log('appId', appId)
  1006. if (appId) {
  1007. setAppValue(appId);
  1008. globalStore.setSelectedAppId(appId);
  1009. chatStore.updateCurrentSession((session: any) => {
  1010. session.appId = appId;
  1011. });
  1012. InitChat(appId);
  1013. }
  1014. }
  1015. }, [])
  1016. useEffect(() => {
  1017. if (appValue !== globalStore.selectedAppId) {
  1018. setAppValue(globalStore.selectedAppId);
  1019. chatStore.updateCurrentSession((session: any) => {
  1020. session.appId = globalStore.selectedAppId;
  1021. });
  1022. InitChat(globalStore.selectedAppId);
  1023. }
  1024. }, [globalStore.selectedAppId])
  1025. const [inputRows, setInputRows] = useState(2);
  1026. const measure = useDebouncedCallback(
  1027. () => {
  1028. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  1029. const inputRows = Math.min(
  1030. 20,
  1031. Math.max(2 + Number(!isMobileScreen), rows),
  1032. );
  1033. setInputRows(inputRows);
  1034. },
  1035. 100,
  1036. {
  1037. leading: true,
  1038. trailing: true,
  1039. },
  1040. );
  1041. // eslint-disable-next-line react-hooks/exhaustive-deps
  1042. useEffect(measure, [userInput]);
  1043. // chat commands shortcuts
  1044. const chatCommands = useChatCommand({
  1045. new: () => chatStore.newSession(),
  1046. newm: () => navigate(Path.MaskChat),
  1047. prev: () => chatStore.nextSession(-1),
  1048. next: () => chatStore.nextSession(1),
  1049. clear: () =>
  1050. chatStore.updateCurrentSession(
  1051. (session) => (session.clearContextIndex = session.messages.length),
  1052. ),
  1053. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  1054. });
  1055. // only search prompts when user input is short
  1056. const SEARCH_TEXT_LIMIT = 30;
  1057. const onInput = (text: string) => {
  1058. setUserInput(text);
  1059. const n = text.trim().length;
  1060. // clear search results
  1061. if (n === 0) {
  1062. setPromptHints([]);
  1063. } else if (text.match(ChatCommandPrefix)) {
  1064. setPromptHints(chatCommands.search(text));
  1065. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  1066. // check if need to trigger auto completion
  1067. if (text.startsWith("/")) {
  1068. let searchText = text.slice(1);
  1069. onSearch(searchText);
  1070. }
  1071. }
  1072. };
  1073. const doSubmit = (userInput: string) => {
  1074. if (userInput.trim() === "") return;
  1075. const matchCommand = chatCommands.match(userInput);
  1076. if (matchCommand.matched) {
  1077. setUserInput("");
  1078. setPromptHints([]);
  1079. matchCommand.invoke();
  1080. return;
  1081. }
  1082. setIsLoading(true);
  1083. chatStore.onUserInput([], userInput, attachImages).then(() => setIsLoading(false));
  1084. setAttachImages([]);
  1085. localStorage.setItem(LAST_INPUT_KEY, userInput);
  1086. setUserInput("");
  1087. setPromptHints([]);
  1088. if (!isMobileScreen) inputRef.current?.focus();
  1089. setAutoScroll(true);
  1090. setSendStatus(true);
  1091. };
  1092. const onPromptSelect = (prompt: RenderPrompt) => {
  1093. setTimeout(() => {
  1094. setPromptHints([]);
  1095. const matchedChatCommand = chatCommands.match(prompt.content);
  1096. if (matchedChatCommand.matched) {
  1097. // if user is selecting a chat command, just trigger it
  1098. matchedChatCommand.invoke();
  1099. setUserInput("");
  1100. } else {
  1101. // or fill the prompt
  1102. setUserInput(prompt.content);
  1103. }
  1104. inputRef.current?.focus();
  1105. }, 30);
  1106. };
  1107. // stop response
  1108. const onUserStop = (messageId: string) => {
  1109. ChatControllerPool.stop(session.id, messageId);
  1110. };
  1111. useEffect(() => {
  1112. chatStore.updateCurrentSession((session) => {
  1113. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  1114. session.messages.forEach((m) => {
  1115. // check if should stop all stale messages
  1116. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  1117. if (m.streaming) {
  1118. m.streaming = false;
  1119. }
  1120. if (m.content.length === 0) {
  1121. m.isError = true;
  1122. m.content = prettyObject({
  1123. error: true,
  1124. message: "empty response",
  1125. });
  1126. }
  1127. }
  1128. });
  1129. // auto sync mask config from global config
  1130. if (session.mask.syncGlobalConfig) {
  1131. console.log("[Mask] syncing from global, name = ", session.mask.name);
  1132. session.mask.modelConfig = { ...config.modelConfig };
  1133. }
  1134. });
  1135. // eslint-disable-next-line react-hooks/exhaustive-deps
  1136. }, []);
  1137. // check if should send message
  1138. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  1139. if (
  1140. e.key === "ArrowUp" &&
  1141. userInput.length <= 0 &&
  1142. !(e.metaKey || e.altKey || e.ctrlKey)
  1143. ) {
  1144. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  1145. e.preventDefault();
  1146. return;
  1147. }
  1148. if (shouldSubmit(e) && promptHints.length === 0) {
  1149. doSubmit(userInput);
  1150. e.preventDefault();
  1151. }
  1152. };
  1153. const onRightClick = (e: any, message: ChatMessage) => {
  1154. // copy to clipboard
  1155. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  1156. if (userInput.length === 0) {
  1157. setUserInput(getMessageTextContent(message));
  1158. }
  1159. e.preventDefault();
  1160. }
  1161. };
  1162. const deleteMessage = (msgId?: string) => {
  1163. chatStore.updateCurrentSession(
  1164. (session) =>
  1165. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  1166. );
  1167. };
  1168. const onDelete = (msgId: string) => {
  1169. deleteMessage(msgId);
  1170. };
  1171. const onResend = (message: ChatMessage) => {
  1172. // when it is resending a message
  1173. // 1. for a user's message, find the next bot response
  1174. // 2. for a bot's message, find the last user's input
  1175. // 3. delete original user input and bot's message
  1176. // 4. resend the user's input
  1177. const resendingIndex = session.messages.findIndex(
  1178. (m) => m.id === message.id,
  1179. );
  1180. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  1181. console.error("[Chat] failed to find resending message", message);
  1182. return;
  1183. }
  1184. let userMessage: ChatMessage | undefined;
  1185. let botMessage: ChatMessage | undefined;
  1186. if (message.role === "assistant") {
  1187. // if it is resending a bot's message, find the user input for it
  1188. botMessage = message;
  1189. for (let i = resendingIndex; i >= 0; i -= 1) {
  1190. if (session.messages[i].role === "user") {
  1191. userMessage = session.messages[i];
  1192. break;
  1193. }
  1194. }
  1195. } else if (message.role === "user") {
  1196. // if it is resending a user's input, find the bot's response
  1197. userMessage = message;
  1198. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  1199. if (session.messages[i].role === "assistant") {
  1200. botMessage = session.messages[i];
  1201. break;
  1202. }
  1203. }
  1204. }
  1205. if (userMessage === undefined) {
  1206. console.error("[Chat] failed to resend", message);
  1207. return;
  1208. }
  1209. // delete the original messages
  1210. deleteMessage(userMessage.id);
  1211. deleteMessage(botMessage?.id);
  1212. // resend the message
  1213. setIsLoading(true);
  1214. const textContent = getMessageTextContent(userMessage);
  1215. const images = getMessageImages(userMessage);
  1216. chatStore.onUserInput([], textContent, images).then(() => setIsLoading(false));
  1217. inputRef.current?.focus();
  1218. };
  1219. const onPinMessage = (message: ChatMessage) => {
  1220. chatStore.updateCurrentSession((session) =>
  1221. session.mask.context.push(message),
  1222. );
  1223. showToast(Locale.Chat.Actions.PinToastContent, {
  1224. text: Locale.Chat.Actions.PinToastAction,
  1225. onClick: () => {
  1226. setShowPromptModal(true);
  1227. },
  1228. });
  1229. };
  1230. const context: RenderMessage[] = useMemo(() => {
  1231. return session.mask.hideContext ? [] : session.mask.context.slice();
  1232. }, [session.mask.context, session.mask.hideContext]);
  1233. const accessStore = useAccessStore();
  1234. if (
  1235. context.length === 0 &&
  1236. session.messages.at(0)?.content !== BOT_HELLO.content
  1237. ) {
  1238. const copiedHello = Object.assign({}, BOT_HELLO);
  1239. if (!accessStore.isAuthorized()) {
  1240. copiedHello.content = Locale.Error.Unauthorized;
  1241. }
  1242. context.push(copiedHello);
  1243. }
  1244. // preview messages
  1245. const renderMessages = useMemo(() => {
  1246. return context.concat(session.messages as RenderMessage[]).concat(
  1247. isLoading
  1248. ? [
  1249. {
  1250. ...createMessage({
  1251. role: "assistant",
  1252. content: "……",
  1253. }),
  1254. preview: true,
  1255. },
  1256. ]
  1257. : [],
  1258. ).concat(
  1259. userInput.length > 0 && config.sendPreviewBubble
  1260. ? [
  1261. {
  1262. ...createMessage({
  1263. role: "user",
  1264. content: userInput,
  1265. }),
  1266. preview: true,
  1267. },
  1268. ]
  1269. : [],
  1270. );
  1271. }, [
  1272. config.sendPreviewBubble,
  1273. context,
  1274. isLoading,
  1275. session.messages,
  1276. userInput,
  1277. ]);
  1278. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1279. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1280. );
  1281. function setMsgRenderIndex(newIndex: number) {
  1282. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1283. newIndex = Math.max(0, newIndex);
  1284. _setMsgRenderIndex(newIndex);
  1285. }
  1286. const messages = useMemo(() => {
  1287. const endRenderIndex = Math.min(
  1288. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1289. renderMessages.length,
  1290. );
  1291. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1292. }, [msgRenderIndex, renderMessages]);
  1293. const onChatBodyScroll = (e: HTMLElement) => {
  1294. const bottomHeight = e.scrollTop + e.clientHeight;
  1295. const edgeThreshold = e.clientHeight;
  1296. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1297. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1298. const isHitBottom =
  1299. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1300. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1301. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1302. if (isTouchTopEdge && !isTouchBottomEdge) {
  1303. setMsgRenderIndex(prevPageMsgIndex);
  1304. } else if (isTouchBottomEdge) {
  1305. setMsgRenderIndex(nextPageMsgIndex);
  1306. }
  1307. setHitBottom(isHitBottom);
  1308. setAutoScroll(isHitBottom);
  1309. };
  1310. function scrollToBottom() {
  1311. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1312. scrollDomToBottom();
  1313. }
  1314. // clear context index = context length + index in messages
  1315. const clearContextIndex =
  1316. (session.clearContextIndex ?? -1) >= 0
  1317. ? session.clearContextIndex! + context.length - msgRenderIndex
  1318. : -1;
  1319. const [showPromptModal, setShowPromptModal] = useState(false);
  1320. const clientConfig = useMemo(() => getClientConfig(), []);
  1321. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1322. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1323. useCommand({
  1324. fill: setUserInput,
  1325. submit: (text) => {
  1326. doSubmit(text);
  1327. },
  1328. code: (text) => {
  1329. if (accessStore.disableFastLink) return;
  1330. console.log("[Command] got code from url: ", text);
  1331. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1332. if (res) {
  1333. accessStore.update((access) => (access.accessCode = text));
  1334. }
  1335. });
  1336. },
  1337. settings: (text) => {
  1338. if (accessStore.disableFastLink) return;
  1339. try {
  1340. const payload = JSON.parse(text) as {
  1341. key?: string;
  1342. url?: string;
  1343. };
  1344. console.log("[Command] got settings from url: ", payload);
  1345. if (payload.key || payload.url) {
  1346. showConfirm(
  1347. Locale.URLCommand.Settings +
  1348. `\n${JSON.stringify(payload, null, 4)}`,
  1349. ).then((res) => {
  1350. if (!res) return;
  1351. if (payload.key) {
  1352. accessStore.update(
  1353. (access) => (access.openaiApiKey = payload.key!),
  1354. );
  1355. }
  1356. if (payload.url) {
  1357. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1358. }
  1359. accessStore.update((access) => (access.useCustomConfig = true));
  1360. });
  1361. }
  1362. } catch {
  1363. console.error("[Command] failed to get settings from url: ", text);
  1364. }
  1365. },
  1366. });
  1367. // edit / insert message modal
  1368. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1369. // remember unfinished input
  1370. useEffect(() => {
  1371. // try to load from local storage
  1372. const key = UNFINISHED_INPUT(session.id);
  1373. const mayBeUnfinishedInput = localStorage.getItem(key);
  1374. if (mayBeUnfinishedInput && userInput.length === 0) {
  1375. setUserInput(mayBeUnfinishedInput);
  1376. localStorage.removeItem(key);
  1377. }
  1378. const dom = inputRef.current;
  1379. return () => {
  1380. localStorage.setItem(key, dom?.value ?? "");
  1381. };
  1382. // eslint-disable-next-line react-hooks/exhaustive-deps
  1383. }, []);
  1384. const handlePaste = useCallback(
  1385. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1386. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1387. if (!isVisionModel(currentModel)) {
  1388. return;
  1389. }
  1390. const items = (event.clipboardData || window.clipboardData).items;
  1391. for (const item of items) {
  1392. if (item.kind === "file" && item.type.startsWith("image/")) {
  1393. event.preventDefault();
  1394. const file = item.getAsFile();
  1395. if (file) {
  1396. const images: string[] = [];
  1397. images.push(...attachImages);
  1398. images.push(
  1399. ...(await new Promise<string[]>((res, rej) => {
  1400. setUploading(true);
  1401. const imagesData: string[] = [];
  1402. uploadImageRemote(file).then((dataUrl) => {
  1403. imagesData.push(dataUrl);
  1404. setUploading(false);
  1405. res(imagesData);
  1406. }).catch((e) => {
  1407. setUploading(false);
  1408. rej(e);
  1409. });
  1410. })),
  1411. );
  1412. const imagesLength = images.length;
  1413. if (imagesLength > 3) {
  1414. images.splice(3, imagesLength - 3);
  1415. }
  1416. setAttachImages(images);
  1417. }
  1418. }
  1419. }
  1420. },
  1421. [attachImages, chatStore],
  1422. );
  1423. async function uploadImage() {
  1424. const images: string[] = [];
  1425. images.push(...attachImages);
  1426. images.push(
  1427. ...(await new Promise<string[]>((res, rej) => {
  1428. const fileInput = document.createElement("input");
  1429. fileInput.type = "file";
  1430. fileInput.accept =
  1431. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1432. fileInput.multiple = true;
  1433. fileInput.onchange = (event: any) => {
  1434. setUploading(true);
  1435. const files = event.target.files;
  1436. const imagesData: string[] = [];
  1437. for (let i = 0; i < files.length; i++) {
  1438. const file = event.target.files[i];
  1439. uploadImageRemote(file).then((dataUrl) => {
  1440. imagesData.push(dataUrl);
  1441. if (
  1442. imagesData.length === 3 ||
  1443. imagesData.length === files.length
  1444. ) {
  1445. setUploading(false);
  1446. res(imagesData);
  1447. }
  1448. }).catch((e) => {
  1449. setUploading(false);
  1450. rej(e);
  1451. });
  1452. }
  1453. };
  1454. fileInput.click();
  1455. })),
  1456. );
  1457. const imagesLength = images.length;
  1458. if (imagesLength > 3) {
  1459. images.splice(3, imagesLength - 3);
  1460. }
  1461. setAttachImages(images);
  1462. }
  1463. const couldStop = ChatControllerPool.hasPending();
  1464. const stopAll = () => ChatControllerPool.stopAll();
  1465. const [isClickStop, setIsClickStop] = useState(false);
  1466. useEffect(() => {
  1467. if (!couldStop) {
  1468. setIsClickStop(false)
  1469. }
  1470. }, [couldStop])
  1471. interface FileIconProps {
  1472. fileName: string;
  1473. }
  1474. const FileIcon: React.FC<FileIconProps> = (props: FileIconProps) => {
  1475. const style = {
  1476. fontSize: '30px',
  1477. color: '#3875f6',
  1478. }
  1479. let icon = <FileOutlined style={style} />
  1480. if (props.fileName) {
  1481. const suffix = props.fileName.split('.').pop() || '';
  1482. switch (suffix) {
  1483. case 'pdf':
  1484. icon = <FilePdfOutlined style={style} />
  1485. break;
  1486. case 'txt':
  1487. icon = <FileTextOutlined style={style} />
  1488. break;
  1489. case 'doc':
  1490. case 'docx':
  1491. icon = <FileWordOutlined style={style} />
  1492. break;
  1493. default:
  1494. break;
  1495. }
  1496. }
  1497. return icon;
  1498. }
  1499. const [drawerOpen, setDrawerOpen] = useState(false);
  1500. const [drawerData, setDrawerData] = useState({
  1501. knowledge_id: '',
  1502. doc_name: '',
  1503. chunk_info: {
  1504. doc_id: '',
  1505. chunk_list: [],
  1506. }
  1507. });
  1508. const SliceDrawer: React.FC = () => {
  1509. const [pageLoading, setPageLoading] = useState(false);
  1510. const [list, setList] = useState([]);
  1511. const InitSlice = async () => {
  1512. setPageLoading(true);
  1513. try {
  1514. const res: any = await api.post('/deepseek/api/slicePage', {
  1515. knowledge_id: drawerData.knowledge_id,
  1516. chunk_info: drawerData.chunk_info,
  1517. pageNum: 1,
  1518. pageSize: 9999,
  1519. });
  1520. // console.log(res.rows, 'res.rows');
  1521. setList(res.rows);
  1522. } catch (error) {
  1523. console.error(error);
  1524. } finally {
  1525. setPageLoading(false);
  1526. }
  1527. }
  1528. useEffect(() => {
  1529. InitSlice();
  1530. }, [])
  1531. return (
  1532. <Drawer
  1533. title={drawerData.doc_name}
  1534. loading={pageLoading}
  1535. open={drawerOpen}
  1536. onClose={() => {
  1537. setDrawerOpen(false);
  1538. }}
  1539. >
  1540. {list.map((item: any, index) => {
  1541. const score = Number(item.rerankScore);
  1542. const formattedScore = isNaN(score) ? '0.00' : (Math.trunc(score * 100) / 100);
  1543. return <div
  1544. style={{
  1545. padding: 10,
  1546. background: '#fafafa',
  1547. borderRadius: 4,
  1548. marginBottom: 10
  1549. }}
  1550. key={item.sliceId}
  1551. >
  1552. <div
  1553. style={{
  1554. display: 'flex',
  1555. justifyContent: 'space-between',
  1556. alignItems: 'center',
  1557. }}
  1558. >
  1559. <div style={{ margin: '5px 0' }} className="flex items-center justify-center">
  1560. <span className="mr-2">片段{index + 1}</span> {item.revisionStatus === '0' && <Tooltip title="已废弃">
  1561. <div className="flex items-center justify-center">
  1562. <Image width={14} height={14} src={rfq.src}
  1563. preview={false}
  1564. className="mr-[10px]"
  1565. onClick={() => {
  1566. // setDeleSlice((prev)=>!prev)
  1567. // setShowSlice(false);
  1568. }} ></Image>
  1569. <Tag color="red" style={{ padding: '0 2px', fontSize: '12px',marginLeft:'5px' }}> 已废弃 </Tag>
  1570. </div>
  1571. </Tooltip>}
  1572. </div>
  1573. <div>
  1574. <StarTwoTone style={{ marginRight: 10 }} />
  1575. rerank得分{formattedScore}
  1576. </div>
  1577. </div>
  1578. <div className={styles['markdown-preview']}>
  1579. {/* {item.sliceText} */}
  1580. <Typography
  1581. className={`text-sm leading-7 text-gray-800 ${styles["markdown-preview"]}`}
  1582. dangerouslySetInnerHTML={{
  1583. __html: marked.render(item.sliceText),
  1584. }}
  1585. />
  1586. {item.parentSection && <p className="text-right mt-[2px]">{item.parentSection}</p>}
  1587. </div>
  1588. {item.revisionStatus === '1' && <div className={styles['markdown-preview']}>
  1589. <div><Image width={18} height={18} src={tubing.src} preview={false} className='cursor-pointer' /></div>
  1590. <h3 className="text-[20px]">{item.refDocumentName}</h3>
  1591. <Typography
  1592. className={`text-sm leading-7 text-gray-800 ${styles["markdown-preview"]}`}
  1593. dangerouslySetInnerHTML={{
  1594. __html: marked.render(item.revisionSliceText),
  1595. }}
  1596. />
  1597. </div>}
  1598. </div>
  1599. })}
  1600. </Drawer>
  1601. )
  1602. }
  1603. useEffect(() => {
  1604. // 当显示欢迎页面时,确保滚动到顶部
  1605. if (messages.length <= 1 && scrollRef.current) {
  1606. setTimeout(() => {
  1607. if (scrollRef.current) {
  1608. scrollRef.current.scrollTo(0, 0);
  1609. }
  1610. }, 0);
  1611. }
  1612. }, [messages.length]);
  1613. const [visibleOut, setVisibleOut] = useState(false);
  1614. const [webSearch, setWebSearch] = useState(false);
  1615. const [deleSliceMap, setDeleSliceMap] = useState<Record<string, boolean>>({});
  1616. const [showSliceMap, setShowSliceMap] = useState<Record<string, boolean>>({});
  1617. return (
  1618. <div className={styles.chat} key={session.id}>
  1619. {
  1620. <div className="window-header" style={{}} data-tauri-drag-region>
  1621. <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: 'auto' }}
  1622. className={`window-header-title ${styles["chat-body-title"]}`}>
  1623. {
  1624. <div style={{ marginRight: 10 }} className="flex items-center ">
  1625. <Button
  1626. type='text'
  1627. icon={<MenuOutlined />}
  1628. onClick={() => {
  1629. globalStore.setShowMenu(!globalStore.showMenu);
  1630. }}
  1631. />
  1632. {/* <p className="cursor-pointer text-[#000000] ml-[6px]"
  1633. onClick={() => {
  1634. globalStore.setSelectedAppId('1881234567890');
  1635. chatStore.clearSessions();
  1636. navigate({ pathname: '/deepseekChat' });
  1637. }}
  1638. > 通用问答 <MessageOutlined /></p> */}
  1639. </div>
  1640. }
  1641. {
  1642. false &&
  1643. <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
  1644. <Select
  1645. style={{ width: '100%', height: 38, marginRight: 10 }}
  1646. value={selectedFruit}
  1647. onChange={(value: "ONLINE" | "LOCAL") => {
  1648. chatStore.clearSessions();
  1649. chatStore.updateCurrentSession((values) => {
  1650. values.appId = globalStore.selectedAppId;
  1651. });
  1652. navigate({ pathname: '/newChat' });
  1653. setSelectedFruit(value);
  1654. chatStore.setChatMode(value);
  1655. }}
  1656. >
  1657. {fruits.map(fruit => (
  1658. <Select.Option key={fruit.id} value={fruit.id}>
  1659. {fruit.name}
  1660. </Select.Option>
  1661. ))}
  1662. </Select>
  1663. {
  1664. appList.length > 0 ?
  1665. <Select
  1666. style={{ width: '100%', height: 38, marginRight: 5 }}
  1667. placeholder='请选择'
  1668. options={appList}
  1669. value={appValue}
  1670. onChange={(value) => {
  1671. setAppValue(value);
  1672. globalStore.setSelectedAppId(value);
  1673. chatStore.clearSessions();
  1674. chatStore.updateCurrentSession((values) => {
  1675. values.appId = value;
  1676. });
  1677. useChatStore.setState({
  1678. message: {
  1679. content: '',
  1680. role: 'assistant',
  1681. }
  1682. });
  1683. setSendStatus(false);
  1684. }}
  1685. />
  1686. :
  1687. null
  1688. }
  1689. </div>
  1690. }
  1691. </div>
  1692. <h3 style={{ color: '#111111', margin: 0, padding: 0 }}>
  1693. {messages.length > 1 ? detail?.name : ''}
  1694. </h3>
  1695. <div className="window-actions">
  1696. <div className="window-action-button">
  1697. <UserOut globalStore={globalStore} chatStore={chatStore}></UserOut>
  1698. {/* <Popover
  1699. trigger="click"
  1700. title="分享该应用"
  1701. content={() => {
  1702. const url = `${window.location.origin}/#/knowledgeChat?showMenu=false&chatMode=${selectedFruit}&appId=${appValue}`
  1703. return <div>
  1704. <div style={{ marginBottom: 10 }}>
  1705. {url}
  1706. </div>
  1707. <Button onClick={() => {
  1708. navigator.clipboard.writeText(url);
  1709. message.success('分享链接已复制到剪贴板');
  1710. }}>
  1711. 复制
  1712. </Button>
  1713. </div>
  1714. }
  1715. }>
  1716. <IconButton
  1717. icon={<ExportIcon />}
  1718. bordered
  1719. title='分享该应用'
  1720. />
  1721. </Popover> */}
  1722. </div>
  1723. {/* {showMaxIcon && (
  1724. <div className="window-action-button">
  1725. <IconButton
  1726. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1727. bordered
  1728. title={Locale.Chat.Actions.FullScreen}
  1729. aria={Locale.Chat.Actions.FullScreen}
  1730. onClick={() => {
  1731. config.update(
  1732. (config) => (config.tightBorder = !config.tightBorder),
  1733. );
  1734. }}
  1735. />
  1736. </div>
  1737. )} */}
  1738. </div>
  1739. {/* <PromptToast
  1740. showToast={!hitBottom}
  1741. showModal={showPromptModal}
  1742. setShowModal={setShowPromptModal}
  1743. /> */}
  1744. </div>
  1745. }
  1746. <div
  1747. className={styles["chat-body"]}
  1748. ref={scrollRef}
  1749. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1750. onMouseDown={() => inputRef.current?.blur()}
  1751. onTouchStart={() => {
  1752. inputRef.current?.blur();
  1753. setAutoScroll(false);
  1754. }}
  1755. >
  1756. {/* 这里是具体的聊天框 */}
  1757. {
  1758. messages.length > 1 ?
  1759. <>
  1760. {messages.map((message, i) => {
  1761. const isUser = message.role === "user";
  1762. const isContext = i < context.length;
  1763. const showActions =
  1764. i > 0 &&
  1765. !(message.preview || message.content.length === 0) &&
  1766. !isContext;
  1767. const showTyping = message.preview || message.streaming;
  1768. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1769. return (
  1770. <Fragment key={message.id}>
  1771. <div
  1772. className={
  1773. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1774. }
  1775. >
  1776. <div className={styles["chat-message-container"]}>
  1777. <div className={styles["chat-message-header"]}>
  1778. <div className={styles["chat-message-avatar"]}>
  1779. {isUser ? (
  1780. // 在这里换头像
  1781. <div style={{ position: 'relative' }}>
  1782. <div
  1783. style={{
  1784. position: 'absolute',
  1785. zIndex: 2,
  1786. top: '50%',
  1787. left: '50%',
  1788. transform: ' translate(-110%, -100%)',
  1789. fontSize: 14,
  1790. }}>
  1791. </div>
  1792. </div>
  1793. ) : (
  1794. <>
  1795. {["system"].includes(message.role) ? (
  1796. <Avatar avatar="2699-fe0f" />
  1797. ) : (
  1798. // 1111
  1799. <MaskAvatar
  1800. avatar={session.mask.avatar}
  1801. model={
  1802. message.model || session.mask.modelConfig.model
  1803. }
  1804. />
  1805. )}
  1806. </>
  1807. )}
  1808. </div>
  1809. {/* {showActions && (
  1810. <div className={styles["chat-message-actions"]}>
  1811. <div className={styles["chat-input-actions"]}>
  1812. {message.streaming ? (
  1813. <ChatAction
  1814. text={Locale.Chat.Actions.Stop}
  1815. icon={<StopIcon />}
  1816. onClick={() => onUserStop(message.id ?? i)}
  1817. />
  1818. ) : (
  1819. <>
  1820. <ChatAction
  1821. text={Locale.Chat.Actions.Retry}
  1822. icon={<ResetIcon />}
  1823. onClick={() => onResend(message)}
  1824. />
  1825. <ChatAction
  1826. text={Locale.Chat.Actions.Delete}
  1827. icon={<DeleteIcon />}
  1828. onClick={() => onDelete(message.id ?? i)}
  1829. />
  1830. <ChatAction
  1831. text={Locale.Chat.Actions.Pin}
  1832. icon={<PinIcon />}
  1833. onClick={() => onPinMessage(message)}
  1834. />
  1835. <ChatAction
  1836. text={Locale.Chat.Actions.Copy}
  1837. icon={<CopyIcon />}
  1838. onClick={() =>
  1839. copyToClipboard(
  1840. getMessageTextContent(message),
  1841. )
  1842. }
  1843. />
  1844. </>
  1845. )}
  1846. </div>
  1847. </div>
  1848. )} */}
  1849. </div>
  1850. {
  1851. showTyping ?
  1852. <div className={styles["chat-message-status"]}>
  1853. {isUser ? '' : '正在查询文档…'}
  1854. </div>
  1855. :
  1856. <div className={styles["chat-message-status"]}>
  1857. {
  1858. message.role === 'assistant' && messages.length - 1 === i &&
  1859. <div>
  1860. <CheckCircleOutlined /> 文档搜索成功
  1861. </div>
  1862. }
  1863. </div>
  1864. }
  1865. <div className={styles["chat-message-item"]}>
  1866. <Markdown
  1867. key={message.streaming ? "loading" : "done"}
  1868. content={getMessageTextContent(message)}
  1869. loading={
  1870. (message.preview || message.streaming) &&
  1871. message.content.length === 0 &&
  1872. !isUser
  1873. }
  1874. // onContextMenu={(e) => onRightClick(e, message)}
  1875. onDoubleClickCapture={() => {
  1876. if (!isMobileScreen) return;
  1877. setUserInput(getMessageTextContent(message));
  1878. }}
  1879. fontSize={fontSize}
  1880. fontFamily={fontFamily}
  1881. parentRef={scrollRef}
  1882. defaultShow={i >= messages.length - 6}
  1883. />
  1884. {getMessageImages(message).length == 1 && (
  1885. <img
  1886. className={styles["chat-message-item-image"]}
  1887. src={getMessageImages(message)[0]}
  1888. alt=""
  1889. />
  1890. )}
  1891. {getMessageImages(message).length > 1 && (
  1892. <div
  1893. className={styles["chat-message-item-images"]}
  1894. style={
  1895. {
  1896. "--image-count": getMessageImages(message).length,
  1897. } as React.CSSProperties
  1898. }
  1899. >
  1900. {getMessageImages(message).map((image, index) => {
  1901. return (
  1902. <img
  1903. className={
  1904. styles["chat-message-item-image-multi"]
  1905. }
  1906. key={index}
  1907. src={image}
  1908. alt=""
  1909. />
  1910. );
  1911. })}
  1912. </div>
  1913. )}
  1914. </div>
  1915. {/* 是否显示按钮 */}
  1916. {!isUser && <div className="ml-2 flex items-center justify-center cursor-pointer mt-2">
  1917. {message?.delSliceInfo?.docDeprecated && message?.delSliceInfo?.docDeprecated.length > 0 && <div className="mr-2 flex items-center justify-center">
  1918. <Tooltip title='废弃内容'>
  1919. <Image width={16} height={16} src={ffq.src}
  1920. preview={false}
  1921. onClick={() => {
  1922. setDeleSliceMap((prev) => ({ ...prev, [message.id]: !prev[message.id] }));
  1923. setShowSliceMap((prev) => ({ ...prev, [message.id]: false }));
  1924. }} ></Image>
  1925. </Tooltip>
  1926. </div>}
  1927. {message.sliceInfo?.docActive && message.sliceInfo?.docActive.length > 0 &&
  1928. <Tooltip title='参考内容'>
  1929. <CopyOutlined onClick={() => {
  1930. setShowSliceMap((prev) => ({ ...prev, [message.id]: !prev[message.id] }));
  1931. setDeleSliceMap((prev) => ({ ...prev, [message.id]: false }));
  1932. }} />
  1933. </Tooltip>
  1934. }
  1935. </div>}
  1936. {
  1937. deleSliceMap[message.id] && message.delSliceInfo?.docDeprecated &&
  1938. <div style={{ marginTop: 10 }}>
  1939. <Collapse
  1940. bordered={false}
  1941. defaultActiveKey={['1']}
  1942. expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
  1943. items={[
  1944. {
  1945. key: '1',
  1946. // label: `查询到“${message.sliceInfo?.doc?.length}条”相关切片`,
  1947. // label: `查询到${message.sliceInfo?.doc?.length}个文档共${message.sliceInfo?.allChunkNum}条切片`,
  1948. label: `以下内容由于已废弃,未参与最终结果输出`,
  1949. children: <div>
  1950. {message.delSliceInfo?.docDeprecated?.map((item, index) => {
  1951. return <div
  1952. style={{
  1953. padding: 10,
  1954. background: '#FFFFFF',
  1955. borderRadius: 4,
  1956. display: 'flex',
  1957. justifyContent: 'space-between',
  1958. alignItems: 'center',
  1959. marginTop: index ? 10 : 0,
  1960. cursor: 'pointer',
  1961. }}
  1962. key={item.doc_id}
  1963. onClick={() => {
  1964. setDrawerData({
  1965. knowledge_id: item!.knowledge_id,
  1966. doc_name: item.doc_name,
  1967. chunk_info: {
  1968. doc_id: item.doc_id,
  1969. chunk_list: item.chunk_info_list,
  1970. }
  1971. });
  1972. setDrawerOpen(true);
  1973. }}
  1974. >
  1975. <div style={{ display: 'flex', alignItems: 'center' }}>
  1976. <FileIcon fileName={item.doc_name} />
  1977. <div style={{ marginLeft: 10 }}>
  1978. {item.doc_name}
  1979. </div>
  1980. </div>
  1981. <div style={{
  1982. padding: 10,
  1983. background: '#FAFAFA',
  1984. borderRadius: 4,
  1985. marginLeft: 20,
  1986. }}>
  1987. {item.chunk_info_list.length}
  1988. </div>
  1989. </div>
  1990. })}
  1991. </div>,
  1992. }
  1993. ]}
  1994. />
  1995. {
  1996. drawerOpen &&
  1997. <SliceDrawer />
  1998. }
  1999. </div>
  2000. }
  2001. {
  2002. showSliceMap[message.id] && message.sliceInfo?.docActive && message.sliceInfo?.docActive.length > 0 &&
  2003. <div style={{ marginTop: 10 }}>
  2004. <Collapse
  2005. bordered={false}
  2006. defaultActiveKey={['1']}
  2007. expandIcon={({ isActive }) => <CaretRightOutlined rotate={isActive ? 90 : 0} />}
  2008. items={[
  2009. {
  2010. key: '1',
  2011. label: `参考文档信息`,
  2012. // label: `查询到${message.sliceInfo?.doc?.length}个文共${message.sliceInfo?.allChunkNum}条切片`,
  2013. // label: `一`,
  2014. children: <div>
  2015. {message.sliceInfo?.docActive?.map((item, index) => {
  2016. return <div
  2017. style={{
  2018. padding: 10,
  2019. background: '#FFFFFF',
  2020. borderRadius: 4,
  2021. display: 'flex',
  2022. justifyContent: 'space-between',
  2023. alignItems: 'center',
  2024. marginTop: index ? 10 : 0,
  2025. cursor: 'pointer',
  2026. }}
  2027. key={item.doc_id}
  2028. onClick={() => {
  2029. setDrawerData({
  2030. knowledge_id: item!.knowledge_id,
  2031. doc_name: item.doc_name,
  2032. chunk_info: {
  2033. doc_id: item.doc_id,
  2034. chunk_list: item.chunk_info_list,
  2035. }
  2036. });
  2037. setDrawerOpen(true);
  2038. }}
  2039. >
  2040. <div style={{ display: 'flex', alignItems: 'center' }}>
  2041. <FileIcon fileName={item.doc_name} />
  2042. <div style={{ marginLeft: 10 }}>
  2043. {item.doc_name}
  2044. </div>
  2045. </div>
  2046. <div style={{
  2047. padding: 10,
  2048. background: '#FAFAFA',
  2049. borderRadius: 4,
  2050. marginLeft: 20,
  2051. }}>
  2052. {item.chunk_info_list.length}
  2053. </div>
  2054. </div>
  2055. })}
  2056. </div>,
  2057. }
  2058. ]}
  2059. />
  2060. {
  2061. drawerOpen &&
  2062. <SliceDrawer />
  2063. }
  2064. </div>
  2065. }
  2066. {/* <div className={styles["chat-message-action-date"]}>
  2067. {isContext
  2068. ? Locale.Chat.IsContext
  2069. : message.date.toLocaleString()}
  2070. </div> */}
  2071. </div>
  2072. </div>
  2073. {shouldShowClearContextDivider && <ClearContextDivider />}
  2074. </Fragment>
  2075. );
  2076. })}
  2077. </>
  2078. :
  2079. <>
  2080. <div style={{ padding: '0 20px' }}>
  2081. <div style={{ display: 'flex', justifyContent: 'center' }}>
  2082. <img style={{ width: 80, height: 80 }} src={avatarSrc.src} />
  2083. </div>
  2084. <h1 style={{ textAlign: 'center' }}>
  2085. {detail?.name}
  2086. </h1>
  2087. <p style={{ textAlign: 'center' }}>
  2088. {detail?.desc}
  2089. </p>
  2090. <div className="flex flex-col items-center justify-center">
  2091. <p className="text-left w-[320px]">我猜您可能想问:</p>
  2092. <>
  2093. {
  2094. questionList.map((item, index) => {
  2095. return (
  2096. <div
  2097. style={{
  2098. width: '300px',
  2099. padding: '10px',
  2100. marginBottom: '10px',
  2101. border: '1px solid #e6e8f1',
  2102. borderRadius: '10px',
  2103. fontSize: '14px',
  2104. display: 'flex',
  2105. justifyContent: 'space-between',
  2106. alignItems: 'center',
  2107. cursor: 'pointer'
  2108. }}
  2109. onClick={() => {
  2110. setUserInput(item.question)
  2111. doSubmit(item.question)
  2112. }}
  2113. key={index}
  2114. >
  2115. <div>
  2116. {item.question}
  2117. </div>
  2118. <RightOutlined />
  2119. </div>
  2120. )
  2121. })
  2122. }
  2123. </>
  2124. </div>
  2125. </div>
  2126. </>
  2127. }
  2128. </div>
  2129. <div className={styles["chat-input-panel"]}>
  2130. {/* <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} /> */}
  2131. <ChatActions
  2132. isClickStop={isClickStop}
  2133. sendStatus={sendStatus}
  2134. setSendStatus={setSendStatus}
  2135. setUserInput={setUserInput}
  2136. doSubmit={doSubmit}
  2137. uploadImage={uploadImage}
  2138. setAttachImages={setAttachImages}
  2139. setUploading={setUploading}
  2140. showPromptModal={() => setShowPromptModal(true)}
  2141. scrollToBottom={scrollToBottom}
  2142. hitBottom={hitBottom}
  2143. uploading={uploading}
  2144. showPromptHints={() => {
  2145. // Click again to close
  2146. if (promptHints.length > 0) {
  2147. setPromptHints([]);
  2148. return;
  2149. }
  2150. inputRef.current?.focus();
  2151. setUserInput("/");
  2152. onSearch("");
  2153. }}
  2154. />
  2155. <label
  2156. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  2157. ? styles["chat-input-panel-inner-attach"]
  2158. : ""
  2159. }`}
  2160. htmlFor="chat-input"
  2161. >
  2162. <textarea
  2163. id="chat-input"
  2164. ref={inputRef}
  2165. className={styles["chat-input"]}
  2166. placeholder={Locale.Chat.Input(submitKey)}
  2167. onInput={(e) => onInput(e.currentTarget.value)}
  2168. value={userInput}
  2169. onKeyDown={onInputKeyDown}
  2170. onFocus={scrollToBottom}
  2171. onClick={scrollToBottom}
  2172. onPaste={handlePaste}
  2173. rows={inputRows}
  2174. autoFocus={autoFocus}
  2175. style={{
  2176. fontSize: config.fontSize,
  2177. fontFamily: config.fontFamily,
  2178. }}
  2179. />
  2180. {attachImages.length != 0 && (
  2181. <div className={styles["attach-images"]}>
  2182. {attachImages.map((image, index) => {
  2183. return (
  2184. <div
  2185. key={index}
  2186. className={styles["attach-image"]}
  2187. style={{ backgroundImage: `url("${image}")` }}
  2188. >
  2189. <div className={styles["attach-image-mask"]}>
  2190. <DeleteImageButton
  2191. deleteImage={() => {
  2192. setAttachImages(
  2193. attachImages.filter((_, i) => i !== index),
  2194. );
  2195. }}
  2196. />
  2197. </div>
  2198. </div>
  2199. );
  2200. })}
  2201. </div>
  2202. )}
  2203. {/*联网搜索按钮*/}
  2204. {/* <div className={styles["chat-input-lianwang"]} style={{
  2205. background: webSearch ? '#dee9fc': '#f3f4f6',
  2206. color: webSearch ? '#3875f6': '#000000',
  2207. }}
  2208. onClick={() => {
  2209. setWebSearch(!webSearch);
  2210. chatStore.setWebSearch(!webSearch);
  2211. }}
  2212. >
  2213. <img src={webSearch ? hlw_selected.src : hlw.src}
  2214. style={{
  2215. width: 16,
  2216. height: 16,
  2217. }}
  2218. />
  2219. <span style={{ fontSize: 11, marginLeft: 5, marginRight: 10 }}>
  2220. 联网搜索
  2221. </span>
  2222. </div> */}
  2223. <div className={styles["chat-input-send"] + ' flex items-center justify-center'}>
  2224. {/* SpeechButton */}
  2225. <SpeechButton
  2226. onResult={(text: string) => {
  2227. // append or set the recognized text into input
  2228. setUserInput((prev) => (prev ? prev + (prev.endsWith(' ') ? '' : ' ') + text : text));
  2229. }}
  2230. />
  2231. <Button disabled={couldStop} className={styles['send_input'] + ' rounded-full'} type="primary" onClick={() => {
  2232. if (couldStop) {
  2233. stopAll();
  2234. setIsClickStop(true);
  2235. } else {
  2236. doSubmit(userInput);
  2237. }
  2238. }} icon={<ArrowUpOutlined />}></Button>
  2239. </div>
  2240. {/* <IconButton
  2241. icon={couldStop ? <div style={{ width: 13, height: 13, background: '#FFFFFF', borderRadius: 2 }}></div> : <SendWhiteIcon />}
  2242. className={styles["chat-input-send"]}
  2243. type="primary"
  2244. onClick={() => {
  2245. if (couldStop) {
  2246. stopAll();
  2247. setIsClickStop(true);
  2248. } else {
  2249. doSubmit(userInput);
  2250. }
  2251. }}
  2252. /> */}
  2253. </label>
  2254. </div>
  2255. <div style={{ paddingBottom: 12, textAlign: 'center', color: '#888888', fontSize: 12 }}>
  2256. 内容由AI生成,仅供参考
  2257. </div>
  2258. {showExport && (
  2259. <ExportMessageModal onClose={() => setShowExport(false)} />
  2260. )}
  2261. {isEditingMessage && (
  2262. <EditMessageModal
  2263. onClose={() => {
  2264. setIsEditingMessage(false);
  2265. }}
  2266. />
  2267. )}
  2268. </div>
  2269. );
  2270. }
  2271. export function Chat() {
  2272. const globalStore = useGlobalStore();
  2273. const chatStore = useChatStore();
  2274. const location = useLocation();
  2275. const sessionIndex = chatStore.currentSessionIndex;
  2276. useEffect(() => {
  2277. chatStore.setModel('BigModel');
  2278. const search = location.search;
  2279. const params = new URLSearchParams(search);
  2280. const showMenu = params.get('showMenu');
  2281. const chatMode = params.get('chatMode');
  2282. if (showMenu) {
  2283. if (showMenu === 'true') {
  2284. globalStore.setShowMenu(true);
  2285. } else if (showMenu === 'false') {
  2286. globalStore.setShowMenu(false);
  2287. }
  2288. } else {
  2289. globalStore.setShowMenu(true);
  2290. }
  2291. if (chatMode) {
  2292. chatStore.setChatMode(chatMode as "ONLINE" | "LOCAL");
  2293. }
  2294. }, []);
  2295. return <_Chat key={sessionIndex}></_Chat>;
  2296. }