chat.tsx 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  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. sendStatus: boolean,
  476. setUserInput: (value: string) => void;
  477. doSubmit: (userInput: string) => void;
  478. uploadImage: () => void;
  479. setAttachImages: (images: string[]) => void;
  480. setUploading: (uploading: boolean) => void;
  481. showPromptModal: () => void;
  482. scrollToBottom: () => void;
  483. showPromptHints: () => void;
  484. hitBottom: boolean;
  485. uploading: boolean;
  486. }) {
  487. const config = useAppConfig();
  488. const navigate = useNavigate();
  489. const chatStore = useChatStore();
  490. // switch themes
  491. const theme = config.theme;
  492. function nextTheme() {
  493. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  494. const themeIndex = themes.indexOf(theme);
  495. const nextIndex = (themeIndex + 1) % themes.length;
  496. const nextTheme = themes[nextIndex];
  497. config.update((config) => (config.theme = nextTheme));
  498. }
  499. // stop all responses
  500. const couldStop = ChatControllerPool.hasPending();
  501. const stopAll = () => ChatControllerPool.stopAll();
  502. // switch model
  503. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  504. const currentProviderName =
  505. chatStore.currentSession().mask.modelConfig?.providerName ||
  506. ServiceProvider.OpenAI;
  507. const allModels = useAllModels();
  508. const models = useMemo(() => {
  509. const filteredModels = allModels.filter((m) => m.available);
  510. const defaultModel = filteredModels.find((m) => m.isDefault);
  511. if (defaultModel) {
  512. const arr = [
  513. defaultModel,
  514. ...filteredModels.filter((m) => m !== defaultModel),
  515. ];
  516. return arr;
  517. } else {
  518. return filteredModels;
  519. }
  520. }, [allModels]);
  521. const currentModelName = useMemo(() => {
  522. const model = models.find(
  523. (m) =>
  524. m.name == currentModel &&
  525. m?.provider?.providerName == currentProviderName,
  526. );
  527. return model?.displayName ?? "";
  528. }, [models, currentModel, currentProviderName]);
  529. const [showModelSelector, setShowModelSelector] = useState(false);
  530. const [showPluginSelector, setShowPluginSelector] = useState(false);
  531. const [showUploadImage, setShowUploadImage] = useState(false);
  532. type GuessList = string[]
  533. const [guessList, setGuessList] = useState<GuessList>([]);
  534. const [showSizeSelector, setShowSizeSelector] = useState(false);
  535. const dalle3Sizes: DalleSize[] = ["1024x1024", "1792x1024", "1024x1792"];
  536. const currentSize =
  537. chatStore.currentSession().mask.modelConfig?.size ?? "1024x1024";
  538. const session = chatStore.currentSession();
  539. useEffect(() => {
  540. const show = isVisionModel(currentModel);
  541. setShowUploadImage(show);
  542. if (!show) {
  543. props.setAttachImages([]);
  544. props.setUploading(false);
  545. }
  546. // if current model is not available
  547. // switch to first available model
  548. const isUnavaliableModel = !models.some((m) => m.name === currentModel);
  549. if (isUnavaliableModel && models.length > 0) {
  550. // show next model to default model if exist
  551. let nextModel = models.find((model) => model.isDefault) || models[0];
  552. chatStore.updateCurrentSession((session) => {
  553. session.mask.modelConfig.model = nextModel.name;
  554. session.mask.modelConfig.providerName = nextModel?.provider?.providerName as ServiceProvider;
  555. });
  556. showToast(
  557. nextModel?.provider?.providerName == "ByteDance"
  558. ? nextModel.displayName
  559. : nextModel.name,
  560. );
  561. }
  562. }, [chatStore, currentModel, models]);
  563. const fetchGuessList = async (record: { content: string; role: string }) => {
  564. try {
  565. const data = {
  566. appId: session.appId,
  567. messages: [
  568. {
  569. content: record.content,
  570. role: record.role,
  571. }
  572. ]
  573. }
  574. let url = '';
  575. if (chatStore.chatMode === 'LOCAL') {
  576. url = '/deepseek/api/async/completions';
  577. } else {
  578. url = '/bigmodel/api/async/completions';
  579. }
  580. const res = await api.post(url, data);
  581. setGuessList(res.data);
  582. } catch (error) {
  583. console.error(error);
  584. }
  585. }
  586. useEffect(() => {
  587. setGuessList([]);
  588. if (chatStore.message.content) {
  589. fetchGuessList(chatStore.message);
  590. }
  591. }, [chatStore.message]);
  592. return (
  593. <div className={styles["chat-input-actions"]}>
  594. {
  595. props.sendStatus &&
  596. <div style={{ color: '#8096ca', fontSize: 13 }}>
  597. <div>
  598. 你还可以尝试提问:
  599. </div>
  600. {
  601. guessList.length === 0 ?
  602. <Space style={{ margin: '10px 0' }}>
  603. <Skeleton.Button size="small" active={true} />
  604. <Skeleton.Button size="small" active={true} />
  605. <Skeleton.Button size="small" active={true} />
  606. </Space>
  607. :
  608. <div style={{ display: 'flex', marginTop: 10, flexWrap: 'wrap' }}>
  609. {
  610. guessList.map((item, index) => {
  611. return (
  612. <div
  613. style={{
  614. padding: '5px 10px',
  615. background: '#f2f4f8',
  616. borderRadius: 5,
  617. margin: '0 10px 10px 0',
  618. cursor: 'pointer',
  619. }}
  620. onClick={() => {
  621. props.setUserInput(item);
  622. props.doSubmit(item)
  623. }}
  624. key={index}
  625. >
  626. {item}
  627. </div>
  628. )
  629. })
  630. }
  631. </div>
  632. }
  633. </div>
  634. }
  635. {/* {couldStop && (
  636. <ChatAction
  637. onClick={stopAll}
  638. text={Locale.Chat.InputActions.Stop}
  639. icon={<StopIcon />}
  640. />
  641. )} */}
  642. {/* {!props.hitBottom && (
  643. <ChatAction
  644. onClick={props.scrollToBottom}
  645. text={Locale.Chat.InputActions.ToBottom}
  646. icon={<BottomIcon />}
  647. />
  648. )} */}
  649. {/* {props.hitBottom && (
  650. <ChatAction
  651. onClick={props.showPromptModal}
  652. text={Locale.Chat.InputActions.Settings}
  653. icon={<SettingsIcon />}
  654. />
  655. )} */}
  656. {/* {showUploadImage && (
  657. <ChatAction
  658. onClick={props.uploadImage}
  659. text={Locale.Chat.InputActions.UploadImage}
  660. icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
  661. />
  662. )} */}
  663. {/* <ChatAction
  664. onClick={nextTheme}
  665. text={Locale.Chat.InputActions.Theme[theme]}
  666. icon={
  667. <>
  668. {theme === Theme.Auto ? (
  669. <AutoIcon />
  670. ) : theme === Theme.Light ? (
  671. <LightIcon />
  672. ) : theme === Theme.Dark ? (
  673. <DarkIcon />
  674. ) : null}
  675. </>
  676. }
  677. /> */}
  678. {/* <CallWord */}
  679. {/* setUserInput={props.setUserInput} */}
  680. {/* doSubmit={props.doSubmit} */}
  681. {/* /> */}
  682. {/* <ChatAction
  683. onClick={props.showPromptHints}
  684. text={Locale.Chat.InputActions.Prompt}
  685. icon={<PromptIcon />}
  686. /> */}
  687. {/* <ChatAction
  688. onClick={() => {
  689. navigate(Path.Masks);
  690. }}
  691. text={Locale.Chat.InputActions.Masks}
  692. icon={<MaskIcon />}
  693. /> */}
  694. {/* <ChatAction
  695. text={Locale.Chat.InputActions.Clear}
  696. icon={<BreakIcon />}
  697. onClick={() => {
  698. chatStore.updateCurrentSession((session) => {
  699. if (session.clearContextIndex === session.messages.length) {
  700. session.clearContextIndex = undefined;
  701. } else {
  702. session.clearContextIndex = session.messages.length;
  703. session.memoryPrompt = ""; // will clear memory
  704. }
  705. });
  706. }}
  707. /> */}
  708. {/* <ChatAction
  709. onClick={() => setShowModelSelector(true)}
  710. text={currentModelName}
  711. icon={<RobotIcon />}
  712. /> */}
  713. {showModelSelector && (
  714. <Selector
  715. defaultSelectedValue={`${currentModel}@${currentProviderName}`}
  716. items={models.map((m) => ({
  717. title: `${m.displayName}${m?.provider?.providerName
  718. ? "(" + m?.provider?.providerName + ")"
  719. : ""
  720. }`,
  721. value: `${m.name}@${m?.provider?.providerName}`,
  722. }))}
  723. onClose={() => setShowModelSelector(false)}
  724. onSelection={(s) => {
  725. if (s.length === 0) return;
  726. const [model, providerName] = s[0].split("@");
  727. chatStore.updateCurrentSession((session) => {
  728. session.mask.modelConfig.model = model as ModelType;
  729. session.mask.modelConfig.providerName =
  730. providerName as ServiceProvider;
  731. session.mask.syncGlobalConfig = false;
  732. });
  733. if (providerName == "ByteDance") {
  734. const selectedModel = models.find(
  735. (m) =>
  736. m.name == model && m?.provider?.providerName == providerName,
  737. );
  738. showToast(selectedModel?.displayName ?? "");
  739. } else {
  740. showToast(model);
  741. }
  742. }}
  743. />
  744. )}
  745. {isDalle3(currentModel) && (
  746. <ChatAction
  747. onClick={() => setShowSizeSelector(true)}
  748. text={currentSize}
  749. icon={<SizeIcon />}
  750. />
  751. )}
  752. {showSizeSelector && (
  753. <Selector
  754. defaultSelectedValue={currentSize}
  755. items={dalle3Sizes.map((m) => ({
  756. title: m,
  757. value: m,
  758. }))}
  759. onClose={() => setShowSizeSelector(false)}
  760. onSelection={(s) => {
  761. if (s.length === 0) return;
  762. const size = s[0];
  763. chatStore.updateCurrentSession((session) => {
  764. session.mask.modelConfig.size = size;
  765. });
  766. showToast(size);
  767. }}
  768. />
  769. )}
  770. {/* <ChatAction
  771. onClick={() => setShowPluginSelector(true)}
  772. text={Locale.Plugin.Name}
  773. icon={<PluginIcon />}
  774. /> */}
  775. {showPluginSelector && (
  776. <Selector
  777. multiple
  778. defaultSelectedValue={chatStore.currentSession().mask?.plugin}
  779. items={[
  780. {
  781. title: Locale.Plugin.Artifacts,
  782. value: Plugin.Artifacts,
  783. },
  784. ]}
  785. onClose={() => setShowPluginSelector(false)}
  786. onSelection={(s) => {
  787. const plugin = s[0];
  788. chatStore.updateCurrentSession((session) => {
  789. session.mask.plugin = s;
  790. });
  791. if (plugin) {
  792. showToast(plugin);
  793. }
  794. }}
  795. />
  796. )}
  797. </div>
  798. );
  799. }
  800. export function EditMessageModal(props: { onClose: () => void }) {
  801. const chatStore = useChatStore();
  802. const session = chatStore.currentSession();
  803. const [messages, setMessages] = useState(session.messages.slice());
  804. return (
  805. <div className="modal-mask">
  806. <Modal
  807. title={Locale.Chat.EditMessage.Title}
  808. onClose={props.onClose}
  809. actions={[
  810. <IconButton
  811. text={Locale.UI.Cancel}
  812. icon={<CancelIcon />}
  813. key="cancel"
  814. onClick={() => {
  815. props.onClose();
  816. }}
  817. />,
  818. <IconButton
  819. type="primary"
  820. text={Locale.UI.Confirm}
  821. icon={<ConfirmIcon />}
  822. key="ok"
  823. onClick={() => {
  824. chatStore.updateCurrentSession(
  825. (session) => (session.messages = messages),
  826. );
  827. props.onClose();
  828. }}
  829. />,
  830. ]}
  831. >
  832. <List>
  833. <ListItem
  834. title={Locale.Chat.EditMessage.Topic.Title}
  835. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  836. >
  837. <input
  838. type="text"
  839. value={session.topic}
  840. onInput={(e) =>
  841. chatStore.updateCurrentSession(
  842. (session) => (session.topic = e.currentTarget.value),
  843. )
  844. }
  845. ></input>
  846. </ListItem>
  847. </List>
  848. <ContextPrompts
  849. context={messages}
  850. updateContext={(updater) => {
  851. const newMessages = messages.slice();
  852. updater(newMessages);
  853. setMessages(newMessages);
  854. }}
  855. />
  856. </Modal>
  857. </div>
  858. );
  859. }
  860. export function DeleteImageButton(props: { deleteImage: () => void }) {
  861. return (
  862. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  863. <DeleteIcon />
  864. </div>
  865. );
  866. }
  867. function _Chat() {
  868. type RenderMessage = ChatMessage & { preview?: boolean };
  869. const chatStore = useChatStore();
  870. const session = chatStore.currentSession();
  871. const config = useAppConfig();
  872. const fontSize = config.fontSize;
  873. const fontFamily = config.fontFamily;
  874. const [showExport, setShowExport] = useState(false);
  875. const inputRef = useRef<HTMLTextAreaElement>(null);
  876. const [userInput, setUserInput] = useState("");
  877. const [isLoading, setIsLoading] = useState(false);
  878. const [sendStatus, setSendStatus] = useState(false);
  879. const { submitKey, shouldSubmit } = useSubmitHandler();
  880. const scrollRef = useRef<HTMLDivElement>(null);
  881. const isScrolledToBottom = scrollRef?.current
  882. ? Math.abs(
  883. scrollRef.current.scrollHeight -
  884. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  885. ) <= 1
  886. : false;
  887. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  888. scrollRef,
  889. isScrolledToBottom,
  890. );
  891. const [hitBottom, setHitBottom] = useState(true);
  892. const isMobileScreen = useMobileScreen();
  893. const navigate = useNavigate();
  894. const [attachImages, setAttachImages] = useState<string[]>([]);
  895. const [uploading, setUploading] = useState(false);
  896. // prompt hints
  897. const promptStore = usePromptStore();
  898. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  899. const onSearch = useDebouncedCallback(
  900. (text: string) => {
  901. const matchedPrompts = promptStore.search(text);
  902. setPromptHints(matchedPrompts);
  903. },
  904. 100,
  905. { leading: true, trailing: true },
  906. );
  907. type AppList = {
  908. label: string,
  909. value: string,
  910. desc: string,
  911. }[];
  912. const [appList, setAppList] = useState<AppList>([]);
  913. const [appValue, setAppValue] = useState<string>();
  914. const globalStore = useGlobalStore();
  915. type QuestionList = string[];
  916. const [questionList, setQuestionList] = useState<QuestionList>([]);
  917. const location = useLocation();
  918. const [loading, setLoading] = useState<boolean>(false);
  919. const fruits = [
  920. { id: 'ONLINE', name: '线上' },
  921. { id: 'LOCAL', name: '本地' },
  922. ];
  923. const [selectedFruit, setSelectedFruit] = React.useState(chatStore.chatMode);
  924. // useEffect(() => {
  925. // }, []);
  926. // 获取应用列表
  927. const fetchApplicationList = async () => {
  928. setLoading(true);
  929. try {
  930. let url = null;
  931. console.log('selectedFruit', selectedFruit);
  932. if (selectedFruit === 'LOCAL') {
  933. url = '/deepseek/api/application/list';
  934. } else {
  935. url = '/bigmodel/api/application/list';
  936. }
  937. const res = await api.get(url);
  938. const list = res.data.filter((item: any) => item.appId !== '1234567890123456789').map((item: any) => {
  939. return {
  940. label: item.name,
  941. value: item.appId,
  942. desc: item.desc,
  943. }
  944. })
  945. setAppList(list);
  946. let appValue = '';
  947. const search = location.search;
  948. if (search.startsWith('?appId=')) {
  949. const value = search.slice(7);
  950. if (list.find((item: any) => item.value === value)) {
  951. appValue = value;
  952. } else {
  953. appValue = list[0]?.value;
  954. }
  955. } else {
  956. appValue = list[0]?.value;
  957. }
  958. setAppValue(appValue);
  959. globalStore.setSelectedAppId(appValue);
  960. chatStore.updateCurrentSession((session) => {
  961. session.appId = appValue;
  962. });
  963. } catch (error) {
  964. console.error(error);
  965. } finally {
  966. setLoading(false);
  967. }
  968. }
  969. // 获取预设问题列表
  970. const fetchDefaultQuestion = async (appId: string) => {
  971. try {
  972. let url = null;
  973. if (selectedFruit === 'LOCAL') {
  974. url = '/deepseek/api/presets';
  975. } else {
  976. url = '/bigmodel/api/presets';
  977. }
  978. const res = await api.get(url + `/${appId}`);
  979. setQuestionList(res.data);
  980. } catch (error) {
  981. console.error(error);
  982. } finally {
  983. setLoading(false);
  984. }
  985. }
  986. const init = async () => {
  987. await fetchApplicationList();
  988. }
  989. useEffect(() => {
  990. init();
  991. }, [])
  992. useEffect(() => {
  993. if (appValue) {
  994. fetchDefaultQuestion(appValue);
  995. }
  996. }, [appValue, chatStore.chatMode])
  997. useEffect(() => {
  998. fetchApplicationList();
  999. }, [chatStore.chatMode])
  1000. const [inputRows, setInputRows] = useState(2);
  1001. const measure = useDebouncedCallback(
  1002. () => {
  1003. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  1004. const inputRows = Math.min(
  1005. 20,
  1006. Math.max(2 + Number(!isMobileScreen), rows),
  1007. );
  1008. setInputRows(inputRows);
  1009. },
  1010. 100,
  1011. {
  1012. leading: true,
  1013. trailing: true,
  1014. },
  1015. );
  1016. // eslint-disable-next-line react-hooks/exhaustive-deps
  1017. useEffect(measure, [userInput]);
  1018. // chat commands shortcuts
  1019. const chatCommands = useChatCommand({
  1020. new: () => chatStore.newSession(),
  1021. newm: () => navigate(Path.NewChat),
  1022. prev: () => chatStore.nextSession(-1),
  1023. next: () => chatStore.nextSession(1),
  1024. clear: () =>
  1025. chatStore.updateCurrentSession(
  1026. (session) => (session.clearContextIndex = session.messages.length),
  1027. ),
  1028. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  1029. });
  1030. // only search prompts when user input is short
  1031. const SEARCH_TEXT_LIMIT = 30;
  1032. const onInput = (text: string) => {
  1033. setUserInput(text);
  1034. const n = text.trim().length;
  1035. // clear search results
  1036. if (n === 0) {
  1037. setPromptHints([]);
  1038. } else if (text.match(ChatCommandPrefix)) {
  1039. setPromptHints(chatCommands.search(text));
  1040. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  1041. // check if need to trigger auto completion
  1042. if (text.startsWith("/")) {
  1043. let searchText = text.slice(1);
  1044. onSearch(searchText);
  1045. }
  1046. }
  1047. };
  1048. const doSubmit = (userInput: string) => {
  1049. if (userInput.trim() === "") return;
  1050. const matchCommand = chatCommands.match(userInput);
  1051. if (matchCommand.matched) {
  1052. setUserInput("");
  1053. setPromptHints([]);
  1054. matchCommand.invoke();
  1055. return;
  1056. }
  1057. setIsLoading(true);
  1058. chatStore.onUserInput([], userInput, attachImages).then(() => setIsLoading(false));
  1059. setAttachImages([]);
  1060. localStorage.setItem(LAST_INPUT_KEY, userInput);
  1061. setUserInput("");
  1062. setPromptHints([]);
  1063. if (!isMobileScreen) inputRef.current?.focus();
  1064. setAutoScroll(true);
  1065. setSendStatus(true);
  1066. };
  1067. const onPromptSelect = (prompt: RenderPrompt) => {
  1068. setTimeout(() => {
  1069. setPromptHints([]);
  1070. const matchedChatCommand = chatCommands.match(prompt.content);
  1071. if (matchedChatCommand.matched) {
  1072. // if user is selecting a chat command, just trigger it
  1073. matchedChatCommand.invoke();
  1074. setUserInput("");
  1075. } else {
  1076. // or fill the prompt
  1077. setUserInput(prompt.content);
  1078. }
  1079. inputRef.current?.focus();
  1080. }, 30);
  1081. };
  1082. // stop response
  1083. const onUserStop = (messageId: string) => {
  1084. ChatControllerPool.stop(session.id, messageId);
  1085. };
  1086. useEffect(() => {
  1087. chatStore.updateCurrentSession((session) => {
  1088. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  1089. session.messages.forEach((m) => {
  1090. // check if should stop all stale messages
  1091. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  1092. if (m.streaming) {
  1093. m.streaming = false;
  1094. }
  1095. if (m.content.length === 0) {
  1096. m.isError = true;
  1097. m.content = prettyObject({
  1098. error: true,
  1099. message: "empty response",
  1100. });
  1101. }
  1102. }
  1103. });
  1104. // auto sync mask config from global config
  1105. if (session.mask.syncGlobalConfig) {
  1106. console.log("[Mask] syncing from global, name = ", session.mask.name);
  1107. session.mask.modelConfig = { ...config.modelConfig };
  1108. }
  1109. });
  1110. // eslint-disable-next-line react-hooks/exhaustive-deps
  1111. }, []);
  1112. // check if should send message
  1113. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  1114. if (
  1115. e.key === "ArrowUp" &&
  1116. userInput.length <= 0 &&
  1117. !(e.metaKey || e.altKey || e.ctrlKey)
  1118. ) {
  1119. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  1120. e.preventDefault();
  1121. return;
  1122. }
  1123. if (shouldSubmit(e) && promptHints.length === 0) {
  1124. doSubmit(userInput);
  1125. e.preventDefault();
  1126. }
  1127. };
  1128. const onRightClick = (e: any, message: ChatMessage) => {
  1129. // copy to clipboard
  1130. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  1131. if (userInput.length === 0) {
  1132. setUserInput(getMessageTextContent(message));
  1133. }
  1134. e.preventDefault();
  1135. }
  1136. };
  1137. const deleteMessage = (msgId?: string) => {
  1138. chatStore.updateCurrentSession(
  1139. (session) =>
  1140. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  1141. );
  1142. };
  1143. const onDelete = (msgId: string) => {
  1144. deleteMessage(msgId);
  1145. };
  1146. const onResend = (message: ChatMessage) => {
  1147. // when it is resending a message
  1148. // 1. for a user's message, find the next bot response
  1149. // 2. for a bot's message, find the last user's input
  1150. // 3. delete original user input and bot's message
  1151. // 4. resend the user's input
  1152. const resendingIndex = session.messages.findIndex(
  1153. (m) => m.id === message.id,
  1154. );
  1155. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  1156. console.error("[Chat] failed to find resending message", message);
  1157. return;
  1158. }
  1159. let userMessage: ChatMessage | undefined;
  1160. let botMessage: ChatMessage | undefined;
  1161. if (message.role === "assistant") {
  1162. // if it is resending a bot's message, find the user input for it
  1163. botMessage = message;
  1164. for (let i = resendingIndex; i >= 0; i -= 1) {
  1165. if (session.messages[i].role === "user") {
  1166. userMessage = session.messages[i];
  1167. break;
  1168. }
  1169. }
  1170. } else if (message.role === "user") {
  1171. // if it is resending a user's input, find the bot's response
  1172. userMessage = message;
  1173. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  1174. if (session.messages[i].role === "assistant") {
  1175. botMessage = session.messages[i];
  1176. break;
  1177. }
  1178. }
  1179. }
  1180. if (userMessage === undefined) {
  1181. console.error("[Chat] failed to resend", message);
  1182. return;
  1183. }
  1184. // delete the original messages
  1185. deleteMessage(userMessage.id);
  1186. deleteMessage(botMessage?.id);
  1187. // resend the message
  1188. setIsLoading(true);
  1189. const textContent = getMessageTextContent(userMessage);
  1190. const images = getMessageImages(userMessage);
  1191. chatStore.onUserInput([], textContent, images).then(() => setIsLoading(false));
  1192. inputRef.current?.focus();
  1193. };
  1194. const onPinMessage = (message: ChatMessage) => {
  1195. chatStore.updateCurrentSession((session) =>
  1196. session.mask.context.push(message),
  1197. );
  1198. showToast(Locale.Chat.Actions.PinToastContent, {
  1199. text: Locale.Chat.Actions.PinToastAction,
  1200. onClick: () => {
  1201. setShowPromptModal(true);
  1202. },
  1203. });
  1204. };
  1205. const context: RenderMessage[] = useMemo(() => {
  1206. return session.mask.hideContext ? [] : session.mask.context.slice();
  1207. }, [session.mask.context, session.mask.hideContext]);
  1208. const accessStore = useAccessStore();
  1209. if (
  1210. context.length === 0 &&
  1211. session.messages.at(0)?.content !== BOT_HELLO.content
  1212. ) {
  1213. const copiedHello = Object.assign({}, BOT_HELLO);
  1214. if (!accessStore.isAuthorized()) {
  1215. copiedHello.content = Locale.Error.Unauthorized;
  1216. }
  1217. context.push(copiedHello);
  1218. }
  1219. // preview messages
  1220. const renderMessages = useMemo(() => {
  1221. return context.concat(session.messages as RenderMessage[]).concat(
  1222. isLoading
  1223. ? [
  1224. {
  1225. ...createMessage({
  1226. role: "assistant",
  1227. content: "……",
  1228. }),
  1229. preview: true,
  1230. },
  1231. ]
  1232. : [],
  1233. ).concat(
  1234. userInput.length > 0 && config.sendPreviewBubble
  1235. ? [
  1236. {
  1237. ...createMessage({
  1238. role: "user",
  1239. content: userInput,
  1240. }),
  1241. preview: true,
  1242. },
  1243. ]
  1244. : [],
  1245. );
  1246. }, [
  1247. config.sendPreviewBubble,
  1248. context,
  1249. isLoading,
  1250. session.messages,
  1251. userInput,
  1252. ]);
  1253. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1254. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1255. );
  1256. function setMsgRenderIndex(newIndex: number) {
  1257. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1258. newIndex = Math.max(0, newIndex);
  1259. _setMsgRenderIndex(newIndex);
  1260. }
  1261. const messages = useMemo(() => {
  1262. const endRenderIndex = Math.min(
  1263. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1264. renderMessages.length,
  1265. );
  1266. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1267. }, [msgRenderIndex, renderMessages]);
  1268. const onChatBodyScroll = (e: HTMLElement) => {
  1269. const bottomHeight = e.scrollTop + e.clientHeight;
  1270. const edgeThreshold = e.clientHeight;
  1271. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1272. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1273. const isHitBottom =
  1274. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1275. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1276. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1277. if (isTouchTopEdge && !isTouchBottomEdge) {
  1278. setMsgRenderIndex(prevPageMsgIndex);
  1279. } else if (isTouchBottomEdge) {
  1280. setMsgRenderIndex(nextPageMsgIndex);
  1281. }
  1282. setHitBottom(isHitBottom);
  1283. setAutoScroll(isHitBottom);
  1284. };
  1285. function scrollToBottom() {
  1286. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1287. scrollDomToBottom();
  1288. }
  1289. // clear context index = context length + index in messages
  1290. const clearContextIndex =
  1291. (session.clearContextIndex ?? -1) >= 0
  1292. ? session.clearContextIndex! + context.length - msgRenderIndex
  1293. : -1;
  1294. const [showPromptModal, setShowPromptModal] = useState(false);
  1295. const clientConfig = useMemo(() => getClientConfig(), []);
  1296. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1297. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1298. useCommand({
  1299. fill: setUserInput,
  1300. submit: (text) => {
  1301. doSubmit(text);
  1302. },
  1303. code: (text) => {
  1304. if (accessStore.disableFastLink) return;
  1305. console.log("[Command] got code from url: ", text);
  1306. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1307. if (res) {
  1308. accessStore.update((access) => (access.accessCode = text));
  1309. }
  1310. });
  1311. },
  1312. settings: (text) => {
  1313. if (accessStore.disableFastLink) return;
  1314. try {
  1315. const payload = JSON.parse(text) as {
  1316. key?: string;
  1317. url?: string;
  1318. };
  1319. console.log("[Command] got settings from url: ", payload);
  1320. if (payload.key || payload.url) {
  1321. showConfirm(
  1322. Locale.URLCommand.Settings +
  1323. `\n${JSON.stringify(payload, null, 4)}`,
  1324. ).then((res) => {
  1325. if (!res) return;
  1326. if (payload.key) {
  1327. accessStore.update(
  1328. (access) => (access.openaiApiKey = payload.key!),
  1329. );
  1330. }
  1331. if (payload.url) {
  1332. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1333. }
  1334. accessStore.update((access) => (access.useCustomConfig = true));
  1335. });
  1336. }
  1337. } catch {
  1338. console.error("[Command] failed to get settings from url: ", text);
  1339. }
  1340. },
  1341. });
  1342. // edit / insert message modal
  1343. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1344. // remember unfinished input
  1345. useEffect(() => {
  1346. // try to load from local storage
  1347. const key = UNFINISHED_INPUT(session.id);
  1348. const mayBeUnfinishedInput = localStorage.getItem(key);
  1349. if (mayBeUnfinishedInput && userInput.length === 0) {
  1350. setUserInput(mayBeUnfinishedInput);
  1351. localStorage.removeItem(key);
  1352. }
  1353. const dom = inputRef.current;
  1354. return () => {
  1355. localStorage.setItem(key, dom?.value ?? "");
  1356. };
  1357. // eslint-disable-next-line react-hooks/exhaustive-deps
  1358. }, []);
  1359. const handlePaste = useCallback(
  1360. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1361. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1362. if (!isVisionModel(currentModel)) {
  1363. return;
  1364. }
  1365. const items = (event.clipboardData || window.clipboardData).items;
  1366. for (const item of items) {
  1367. if (item.kind === "file" && item.type.startsWith("image/")) {
  1368. event.preventDefault();
  1369. const file = item.getAsFile();
  1370. if (file) {
  1371. const images: string[] = [];
  1372. images.push(...attachImages);
  1373. images.push(
  1374. ...(await new Promise<string[]>((res, rej) => {
  1375. setUploading(true);
  1376. const imagesData: string[] = [];
  1377. uploadImageRemote(file).then((dataUrl) => {
  1378. imagesData.push(dataUrl);
  1379. setUploading(false);
  1380. res(imagesData);
  1381. }).catch((e) => {
  1382. setUploading(false);
  1383. rej(e);
  1384. });
  1385. })),
  1386. );
  1387. const imagesLength = images.length;
  1388. if (imagesLength > 3) {
  1389. images.splice(3, imagesLength - 3);
  1390. }
  1391. setAttachImages(images);
  1392. }
  1393. }
  1394. }
  1395. },
  1396. [attachImages, chatStore],
  1397. );
  1398. async function uploadImage() {
  1399. const images: string[] = [];
  1400. images.push(...attachImages);
  1401. images.push(
  1402. ...(await new Promise<string[]>((res, rej) => {
  1403. const fileInput = document.createElement("input");
  1404. fileInput.type = "file";
  1405. fileInput.accept =
  1406. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1407. fileInput.multiple = true;
  1408. fileInput.onchange = (event: any) => {
  1409. setUploading(true);
  1410. const files = event.target.files;
  1411. const imagesData: string[] = [];
  1412. for (let i = 0; i < files.length; i++) {
  1413. const file = event.target.files[i];
  1414. uploadImageRemote(file).then((dataUrl) => {
  1415. imagesData.push(dataUrl);
  1416. if (
  1417. imagesData.length === 3 ||
  1418. imagesData.length === files.length
  1419. ) {
  1420. setUploading(false);
  1421. res(imagesData);
  1422. }
  1423. }).catch((e) => {
  1424. setUploading(false);
  1425. rej(e);
  1426. });
  1427. }
  1428. };
  1429. fileInput.click();
  1430. })),
  1431. );
  1432. const imagesLength = images.length;
  1433. if (imagesLength > 3) {
  1434. images.splice(3, imagesLength - 3);
  1435. }
  1436. setAttachImages(images);
  1437. }
  1438. const getAppName = () => {
  1439. const item = appList.find(item => item.value === appValue);
  1440. if (!item) {
  1441. return
  1442. }
  1443. return item.label;
  1444. }
  1445. const getDesc = (value: string) => {
  1446. return appList.find(item => item.value === value)?.desc;
  1447. }
  1448. const couldStop = ChatControllerPool.hasPending();
  1449. const stopAll = () => ChatControllerPool.stopAll();
  1450. return (
  1451. <div className={styles.chat} key={session.id}>
  1452. <div className="window-header" data-tauri-drag-region>
  1453. <div style={{ display: 'flex', alignItems: 'center' }}
  1454. className={`window-header-title ${styles["chat-body-title"]}`}>
  1455. <div>
  1456. {
  1457. isMobileScreen &&
  1458. <IconButton
  1459. style={{ padding: 0, marginRight: 20 }}
  1460. icon={<LeftIcon />}
  1461. text={Locale.NewChat.Return}
  1462. onClick={() => navigate('/knowledgeChat')}
  1463. />
  1464. }
  1465. </div>
  1466. <div>
  1467. <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
  1468. <Select
  1469. style={{ width: '100%', height: 38, marginRight: 5 }}
  1470. value={selectedFruit}
  1471. onChange={(value: "ONLINE" | "LOCAL") => {
  1472. chatStore.clearSessions();
  1473. chatStore.updateCurrentSession((values) => {
  1474. values.appId = globalStore.selectedAppId;
  1475. });
  1476. navigate({ pathname: '/newChat' });
  1477. setSelectedFruit(value);
  1478. chatStore.setChatMode(value);
  1479. }}
  1480. >
  1481. {fruits.map(fruit => (
  1482. <Select.Option key={fruit.id} value={fruit.id}>
  1483. {fruit.name}
  1484. </Select.Option>
  1485. ))}
  1486. </Select>
  1487. {
  1488. appList.length > 0 ?
  1489. <Select
  1490. style={{ width: '100%', height: 38, marginRight: 5 }}
  1491. placeholder='请选择'
  1492. options={appList}
  1493. value={appValue}
  1494. onChange={(value) => {
  1495. setAppValue(value);
  1496. globalStore.setSelectedAppId(value);
  1497. chatStore.clearSessions();
  1498. chatStore.updateCurrentSession((values) => {
  1499. values.appId = value;
  1500. });
  1501. useChatStore.setState({
  1502. message: {
  1503. content: '',
  1504. role: 'assistant',
  1505. }
  1506. });
  1507. setSendStatus(false);
  1508. }}
  1509. />
  1510. :
  1511. null
  1512. }
  1513. </div>
  1514. </div>
  1515. </div>
  1516. <div className="window-actions">
  1517. <div className="window-action-button">
  1518. <Popover
  1519. trigger="click"
  1520. title="分享"
  1521. content={() => {
  1522. const url = `${window.location.origin}/#/knowledgeChat?appId=${appValue}`
  1523. return <div>
  1524. <div style={{ marginBottom: 10 }}>
  1525. {url}
  1526. </div>
  1527. <Button onClick={() => {
  1528. navigator.clipboard.writeText(url);
  1529. message.success('分享链接已复制到剪贴板');
  1530. }}>
  1531. 复制
  1532. </Button>
  1533. </div>
  1534. }
  1535. }>
  1536. <IconButton
  1537. icon={<ExportIcon />}
  1538. bordered
  1539. title={Locale.Chat.Actions.Export}
  1540. />
  1541. </Popover>
  1542. </div>
  1543. {/* {showMaxIcon && (
  1544. <div className="window-action-button">
  1545. <IconButton
  1546. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1547. bordered
  1548. title={Locale.Chat.Actions.FullScreen}
  1549. aria={Locale.Chat.Actions.FullScreen}
  1550. onClick={() => {
  1551. config.update(
  1552. (config) => (config.tightBorder = !config.tightBorder),
  1553. );
  1554. }}
  1555. />
  1556. </div>
  1557. )} */}
  1558. </div>
  1559. {/* <PromptToast
  1560. showToast={!hitBottom}
  1561. showModal={showPromptModal}
  1562. setShowModal={setShowPromptModal}
  1563. /> */}
  1564. </div>
  1565. <div
  1566. className={styles["chat-body"]}
  1567. ref={scrollRef}
  1568. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1569. onMouseDown={() => inputRef.current?.blur()}
  1570. onTouchStart={() => {
  1571. inputRef.current?.blur();
  1572. setAutoScroll(false);
  1573. }}
  1574. >
  1575. {
  1576. messages.length > 1 ?
  1577. <>
  1578. {messages.map((message, i) => {
  1579. const isUser = message.role === "user";
  1580. const isContext = i < context.length;
  1581. const showActions =
  1582. i > 0 &&
  1583. !(message.preview || message.content.length === 0) &&
  1584. !isContext;
  1585. const showTyping = message.preview || message.streaming;
  1586. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1587. return (
  1588. <Fragment key={message.id}>
  1589. <div
  1590. className={
  1591. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1592. }
  1593. >
  1594. <div className={styles["chat-message-container"]}>
  1595. <div className={styles["chat-message-header"]}>
  1596. <div className={styles["chat-message-avatar"]}>
  1597. {/* <div className={styles["chat-message-edit"]}>
  1598. <IconButton
  1599. icon={<EditIcon />}
  1600. aria={Locale.Chat.Actions.Edit}
  1601. onClick={async () => {
  1602. const newMessage = await showPrompt(
  1603. Locale.Chat.Actions.Edit,
  1604. getMessageTextContent(message),
  1605. 10,
  1606. );
  1607. let newContent: string | MultimodalContent[] =
  1608. newMessage;
  1609. const images = getMessageImages(message);
  1610. if (images.length > 0) {
  1611. newContent = [{ type: "text", text: newMessage }];
  1612. for (let i = 0; i < images.length; i++) {
  1613. newContent.push({
  1614. type: "image_url",
  1615. image_url: {
  1616. url: images[i],
  1617. },
  1618. });
  1619. }
  1620. }
  1621. chatStore.updateCurrentSession((session) => {
  1622. const m = session.mask.context
  1623. .concat(session.messages)
  1624. .find((m) => m.id === message.id);
  1625. if (m) {
  1626. m.content = newContent;
  1627. }
  1628. });
  1629. }}
  1630. ></IconButton>
  1631. </div> */}
  1632. {isUser ? (
  1633. // 在这里换头像
  1634. <div style={{ position: 'relative' }}>
  1635. {/* <MaskAvatar */}
  1636. {/* avatar={session.mask.avatar} */}
  1637. {/* /> */}
  1638. {/* <div */}
  1639. {/* style={{ */}
  1640. {/* position: 'absolute', */}
  1641. {/* zIndex: 2, */}
  1642. {/* top: '50%', */}
  1643. {/* left: '50%', */}
  1644. {/* transform: ' translate(-50%, -50%)', */}
  1645. {/* fontSize: 14, */}
  1646. {/* }}> */}
  1647. {/* 我 */}
  1648. {/* </div> */}
  1649. <div
  1650. style={{
  1651. position: 'absolute',
  1652. zIndex: 2,
  1653. top: '50%',
  1654. left: '50%',
  1655. transform: ' translate(-110%, -100%)',
  1656. fontSize: 14,
  1657. }}>
  1658. </div>
  1659. </div>
  1660. ) : (
  1661. <>
  1662. {["system"].includes(message.role) ? (
  1663. <Avatar avatar="2699-fe0f" />
  1664. ) : (
  1665. <MaskAvatar
  1666. avatar={session.mask.avatar}
  1667. model={
  1668. message.model || session.mask.modelConfig.model
  1669. }
  1670. />
  1671. )}
  1672. </>
  1673. )}
  1674. </div>
  1675. {/* {showActions && (
  1676. <div className={styles["chat-message-actions"]}>
  1677. <div className={styles["chat-input-actions"]}>
  1678. {message.streaming ? (
  1679. <ChatAction
  1680. text={Locale.Chat.Actions.Stop}
  1681. icon={<StopIcon />}
  1682. onClick={() => onUserStop(message.id ?? i)}
  1683. />
  1684. ) : (
  1685. <>
  1686. <ChatAction
  1687. text={Locale.Chat.Actions.Retry}
  1688. icon={<ResetIcon />}
  1689. onClick={() => onResend(message)}
  1690. />
  1691. <ChatAction
  1692. text={Locale.Chat.Actions.Delete}
  1693. icon={<DeleteIcon />}
  1694. onClick={() => onDelete(message.id ?? i)}
  1695. />
  1696. <ChatAction
  1697. text={Locale.Chat.Actions.Pin}
  1698. icon={<PinIcon />}
  1699. onClick={() => onPinMessage(message)}
  1700. />
  1701. <ChatAction
  1702. text={Locale.Chat.Actions.Copy}
  1703. icon={<CopyIcon />}
  1704. onClick={() =>
  1705. copyToClipboard(
  1706. getMessageTextContent(message),
  1707. )
  1708. }
  1709. />
  1710. </>
  1711. )}
  1712. </div>
  1713. </div>
  1714. )} */}
  1715. </div>
  1716. {
  1717. showTyping ?
  1718. <div className={styles["chat-message-status"]}>
  1719. {isUser ? '正在输入…' : '正在查询文档…'}
  1720. </div>
  1721. :
  1722. <div className={styles["chat-message-status"]}>
  1723. {
  1724. message.role === 'assistant' && messages.length - 1 === i &&
  1725. <div>
  1726. <CheckCircleOutlined /> 文档搜索成功
  1727. </div>
  1728. }
  1729. </div>
  1730. }
  1731. <div className={styles["chat-message-item"]}>
  1732. <Markdown
  1733. key={message.streaming ? "loading" : "done"}
  1734. content={getMessageTextContent(message)}
  1735. loading={
  1736. (message.preview || message.streaming) &&
  1737. message.content.length === 0 &&
  1738. !isUser
  1739. }
  1740. // onContextMenu={(e) => onRightClick(e, message)}
  1741. onDoubleClickCapture={() => {
  1742. if (!isMobileScreen) return;
  1743. setUserInput(getMessageTextContent(message));
  1744. }}
  1745. fontSize={fontSize}
  1746. fontFamily={fontFamily}
  1747. parentRef={scrollRef}
  1748. defaultShow={i >= messages.length - 6}
  1749. />
  1750. {getMessageImages(message).length == 1 && (
  1751. <img
  1752. className={styles["chat-message-item-image"]}
  1753. src={getMessageImages(message)[0]}
  1754. alt=""
  1755. />
  1756. )}
  1757. {getMessageImages(message).length > 1 && (
  1758. <div
  1759. className={styles["chat-message-item-images"]}
  1760. style={
  1761. {
  1762. "--image-count": getMessageImages(message).length,
  1763. } as React.CSSProperties
  1764. }
  1765. >
  1766. {getMessageImages(message).map((image, index) => {
  1767. return (
  1768. <img
  1769. className={
  1770. styles["chat-message-item-image-multi"]
  1771. }
  1772. key={index}
  1773. src={image}
  1774. alt=""
  1775. />
  1776. );
  1777. })}
  1778. </div>
  1779. )}
  1780. </div>
  1781. {/* <div className={styles["chat-message-action-date"]}>
  1782. {isContext
  1783. ? Locale.Chat.IsContext
  1784. : message.date.toLocaleString()}
  1785. </div> */}
  1786. </div>
  1787. </div>
  1788. {shouldShowClearContextDivider && <ClearContextDivider />}
  1789. </Fragment>
  1790. );
  1791. })}
  1792. </>
  1793. :
  1794. <>
  1795. <div style={{ padding: '0 20px' }}>
  1796. <div style={{ display: 'flex', justifyContent: 'center' }}>
  1797. <img style={{ width: 80, height: 80 }} src={avatarSrc.src} />
  1798. </div>
  1799. <h1 style={{ textAlign: 'center' }}>
  1800. {getAppName()}
  1801. </h1>
  1802. {/* <p style={{ textAlign: 'center' }}>
  1803. 您好,欢迎使用建科·小智使用知识库创建的{getAppName()}
  1804. </p> */}
  1805. <p style={{ textAlign: 'center' }}>
  1806. {appValue ? getDesc(appValue) : ''}
  1807. </p>
  1808. <p>我猜您可能想问:</p>
  1809. {
  1810. questionList.map((item, index) => {
  1811. return (
  1812. <div
  1813. style={{
  1814. padding: '10px',
  1815. marginBottom: '10px',
  1816. border: '1px solid #e6e8f1',
  1817. borderRadius: '10px',
  1818. fontSize: '16px',
  1819. display: 'flex',
  1820. justifyContent: 'space-between',
  1821. alignItems: 'center',
  1822. cursor: 'pointer'
  1823. }}
  1824. onClick={() => {
  1825. setUserInput(item)
  1826. doSubmit(item)
  1827. }}
  1828. key={index}
  1829. >
  1830. <div>
  1831. {item}
  1832. </div>
  1833. <RightOutlined />
  1834. </div>
  1835. )
  1836. })
  1837. }
  1838. </div>
  1839. </>
  1840. }
  1841. </div>
  1842. <div className={styles["chat-input-panel"]}>
  1843. {/* <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} /> */}
  1844. <ChatActions
  1845. sendStatus={sendStatus}
  1846. setUserInput={setUserInput}
  1847. doSubmit={doSubmit}
  1848. uploadImage={uploadImage}
  1849. setAttachImages={setAttachImages}
  1850. setUploading={setUploading}
  1851. showPromptModal={() => setShowPromptModal(true)}
  1852. scrollToBottom={scrollToBottom}
  1853. hitBottom={hitBottom}
  1854. uploading={uploading}
  1855. showPromptHints={() => {
  1856. // Click again to close
  1857. if (promptHints.length > 0) {
  1858. setPromptHints([]);
  1859. return;
  1860. }
  1861. inputRef.current?.focus();
  1862. setUserInput("/");
  1863. onSearch("");
  1864. }}
  1865. />
  1866. <label
  1867. className={`${styles["chat-input-panel-inner"]} ${attachImages.length != 0
  1868. ? styles["chat-input-panel-inner-attach"]
  1869. : ""
  1870. }`}
  1871. htmlFor="chat-input"
  1872. >
  1873. <textarea
  1874. id="chat-input"
  1875. ref={inputRef}
  1876. className={styles["chat-input"]}
  1877. placeholder={Locale.Chat.Input(submitKey)}
  1878. onInput={(e) => onInput(e.currentTarget.value)}
  1879. value={userInput}
  1880. onKeyDown={onInputKeyDown}
  1881. onFocus={scrollToBottom}
  1882. onClick={scrollToBottom}
  1883. onPaste={handlePaste}
  1884. rows={inputRows}
  1885. autoFocus={autoFocus}
  1886. style={{
  1887. fontSize: config.fontSize,
  1888. fontFamily: config.fontFamily,
  1889. }}
  1890. />
  1891. {attachImages.length != 0 && (
  1892. <div className={styles["attach-images"]}>
  1893. {attachImages.map((image, index) => {
  1894. return (
  1895. <div
  1896. key={index}
  1897. className={styles["attach-image"]}
  1898. style={{ backgroundImage: `url("${image}")` }}
  1899. >
  1900. <div className={styles["attach-image-mask"]}>
  1901. <DeleteImageButton
  1902. deleteImage={() => {
  1903. setAttachImages(
  1904. attachImages.filter((_, i) => i !== index),
  1905. );
  1906. }}
  1907. />
  1908. </div>
  1909. </div>
  1910. );
  1911. })}
  1912. </div>
  1913. )}
  1914. <IconButton
  1915. icon={couldStop ? <div style={{ width: 13, height: 13, background: '#FFFFFF', borderRadius: 2 }}></div> : <SendWhiteIcon />}
  1916. text={couldStop ? '停止' : '发送'}
  1917. className={styles["chat-input-send"]}
  1918. type="primary"
  1919. onClick={() => {
  1920. if (couldStop) {
  1921. stopAll();
  1922. } else {
  1923. doSubmit(userInput);
  1924. }
  1925. }}
  1926. />
  1927. </label>
  1928. </div>
  1929. <div style={{ paddingBottom: 20, textAlign: 'center', color: '#888888', fontSize: 12 }}>
  1930. 内容由AI生成,仅供参考
  1931. </div>
  1932. {showExport && (
  1933. <ExportMessageModal onClose={() => setShowExport(false)} />
  1934. )}
  1935. {isEditingMessage && (
  1936. <EditMessageModal
  1937. onClose={() => {
  1938. setIsEditingMessage(false);
  1939. }}
  1940. />
  1941. )}
  1942. </div>
  1943. );
  1944. }
  1945. export function Chat() {
  1946. const chatStore = useChatStore();
  1947. const sessionIndex = chatStore.currentSessionIndex;
  1948. useEffect(() => {
  1949. chatStore.setModel('BigModel');
  1950. }, []);
  1951. return <_Chat key={sessionIndex}></_Chat>;
  1952. }