chat.tsx 64 KB

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