chat.tsx 67 KB

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