chat.tsx 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072
  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. <ChatAction
  733. onClick={() => props.setShowChatSidePanel(true)}
  734. text={"Realtime Chat"}
  735. icon={<HeadphoneIcon />}
  736. />
  737. </div>
  738. </div>
  739. );
  740. }
  741. export function EditMessageModal(props: { onClose: () => void }) {
  742. const chatStore = useChatStore();
  743. const session = chatStore.currentSession();
  744. const [messages, setMessages] = useState(session.messages.slice());
  745. return (
  746. <div className="modal-mask">
  747. <Modal
  748. title={Locale.Chat.EditMessage.Title}
  749. onClose={props.onClose}
  750. actions={[
  751. <IconButton
  752. text={Locale.UI.Cancel}
  753. icon={<CancelIcon />}
  754. key="cancel"
  755. onClick={() => {
  756. props.onClose();
  757. }}
  758. />,
  759. <IconButton
  760. type="primary"
  761. text={Locale.UI.Confirm}
  762. icon={<ConfirmIcon />}
  763. key="ok"
  764. onClick={() => {
  765. chatStore.updateTargetSession(
  766. session,
  767. (session) => (session.messages = messages),
  768. );
  769. props.onClose();
  770. }}
  771. />,
  772. ]}
  773. >
  774. <List>
  775. <ListItem
  776. title={Locale.Chat.EditMessage.Topic.Title}
  777. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  778. >
  779. <input
  780. type="text"
  781. value={session.topic}
  782. onInput={(e) =>
  783. chatStore.updateTargetSession(
  784. session,
  785. (session) => (session.topic = e.currentTarget.value),
  786. )
  787. }
  788. ></input>
  789. </ListItem>
  790. </List>
  791. <ContextPrompts
  792. context={messages}
  793. updateContext={(updater) => {
  794. const newMessages = messages.slice();
  795. updater(newMessages);
  796. setMessages(newMessages);
  797. }}
  798. />
  799. </Modal>
  800. </div>
  801. );
  802. }
  803. export function DeleteImageButton(props: { deleteImage: () => void }) {
  804. return (
  805. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  806. <DeleteIcon />
  807. </div>
  808. );
  809. }
  810. export function ShortcutKeyModal(props: { onClose: () => void }) {
  811. const isMac = navigator.platform.toUpperCase().indexOf("MAC") >= 0;
  812. const shortcuts = [
  813. {
  814. title: Locale.Chat.ShortcutKey.newChat,
  815. keys: isMac ? ["⌘", "Shift", "O"] : ["Ctrl", "Shift", "O"],
  816. },
  817. { title: Locale.Chat.ShortcutKey.focusInput, keys: ["Shift", "Esc"] },
  818. {
  819. title: Locale.Chat.ShortcutKey.copyLastCode,
  820. keys: isMac ? ["⌘", "Shift", ";"] : ["Ctrl", "Shift", ";"],
  821. },
  822. {
  823. title: Locale.Chat.ShortcutKey.copyLastMessage,
  824. keys: isMac ? ["⌘", "Shift", "C"] : ["Ctrl", "Shift", "C"],
  825. },
  826. {
  827. title: Locale.Chat.ShortcutKey.showShortcutKey,
  828. keys: isMac ? ["⌘", "/"] : ["Ctrl", "/"],
  829. },
  830. ];
  831. return (
  832. <div className="modal-mask">
  833. <Modal
  834. title={Locale.Chat.ShortcutKey.Title}
  835. onClose={props.onClose}
  836. actions={[
  837. <IconButton
  838. type="primary"
  839. text={Locale.UI.Confirm}
  840. icon={<ConfirmIcon />}
  841. key="ok"
  842. onClick={() => {
  843. props.onClose();
  844. }}
  845. />,
  846. ]}
  847. >
  848. <div className={styles["shortcut-key-container"]}>
  849. <div className={styles["shortcut-key-grid"]}>
  850. {shortcuts.map((shortcut, index) => (
  851. <div key={index} className={styles["shortcut-key-item"]}>
  852. <div className={styles["shortcut-key-title"]}>
  853. {shortcut.title}
  854. </div>
  855. <div className={styles["shortcut-key-keys"]}>
  856. {shortcut.keys.map((key, i) => (
  857. <div key={i} className={styles["shortcut-key"]}>
  858. <span>{key}</span>
  859. </div>
  860. ))}
  861. </div>
  862. </div>
  863. ))}
  864. </div>
  865. </div>
  866. </Modal>
  867. </div>
  868. );
  869. }
  870. function _Chat() {
  871. type RenderMessage = ChatMessage & { preview?: boolean };
  872. const chatStore = useChatStore();
  873. const session = chatStore.currentSession();
  874. const config = useAppConfig();
  875. const fontSize = config.fontSize;
  876. const fontFamily = config.fontFamily;
  877. const [showExport, setShowExport] = useState(false);
  878. const inputRef = useRef<HTMLTextAreaElement>(null);
  879. const [userInput, setUserInput] = useState("");
  880. const [isLoading, setIsLoading] = useState(false);
  881. const { submitKey, shouldSubmit } = useSubmitHandler();
  882. const scrollRef = useRef<HTMLDivElement>(null);
  883. const isScrolledToBottom = scrollRef?.current
  884. ? Math.abs(
  885. scrollRef.current.scrollHeight -
  886. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  887. ) <= 1
  888. : false;
  889. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  890. scrollRef,
  891. isScrolledToBottom,
  892. );
  893. const [hitBottom, setHitBottom] = useState(true);
  894. const isMobileScreen = useMobileScreen();
  895. const navigate = useNavigate();
  896. const [attachImages, setAttachImages] = useState<string[]>([]);
  897. const [uploading, setUploading] = useState(false);
  898. // prompt hints
  899. const promptStore = usePromptStore();
  900. const [promptHints, setPromptHints] = useState<RenderPrompt[]>([]);
  901. const onSearch = useDebouncedCallback(
  902. (text: string) => {
  903. const matchedPrompts = promptStore.search(text);
  904. setPromptHints(matchedPrompts);
  905. },
  906. 100,
  907. { leading: true, trailing: true },
  908. );
  909. // auto grow input
  910. const [inputRows, setInputRows] = useState(2);
  911. const measure = useDebouncedCallback(
  912. () => {
  913. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  914. const inputRows = Math.min(
  915. 20,
  916. Math.max(2 + Number(!isMobileScreen), rows),
  917. );
  918. setInputRows(inputRows);
  919. },
  920. 100,
  921. {
  922. leading: true,
  923. trailing: true,
  924. },
  925. );
  926. // eslint-disable-next-line react-hooks/exhaustive-deps
  927. useEffect(measure, [userInput]);
  928. // chat commands shortcuts
  929. const chatCommands = useChatCommand({
  930. new: () => chatStore.newSession(),
  931. newm: () => navigate(Path.NewChat),
  932. prev: () => chatStore.nextSession(-1),
  933. next: () => chatStore.nextSession(1),
  934. clear: () =>
  935. chatStore.updateTargetSession(
  936. session,
  937. (session) => (session.clearContextIndex = session.messages.length),
  938. ),
  939. fork: () => chatStore.forkSession(),
  940. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  941. });
  942. // only search prompts when user input is short
  943. const SEARCH_TEXT_LIMIT = 30;
  944. const onInput = (text: string) => {
  945. setUserInput(text);
  946. const n = text.trim().length;
  947. // clear search results
  948. if (n === 0) {
  949. setPromptHints([]);
  950. } else if (text.match(ChatCommandPrefix)) {
  951. setPromptHints(chatCommands.search(text));
  952. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  953. // check if need to trigger auto completion
  954. if (text.startsWith("/")) {
  955. let searchText = text.slice(1);
  956. onSearch(searchText);
  957. }
  958. }
  959. };
  960. const doSubmit = (userInput: string) => {
  961. if (userInput.trim() === "" && isEmpty(attachImages)) return;
  962. const matchCommand = chatCommands.match(userInput);
  963. if (matchCommand.matched) {
  964. setUserInput("");
  965. setPromptHints([]);
  966. matchCommand.invoke();
  967. return;
  968. }
  969. setIsLoading(true);
  970. chatStore
  971. .onUserInput(userInput, attachImages)
  972. .then(() => setIsLoading(false));
  973. setAttachImages([]);
  974. chatStore.setLastInput(userInput);
  975. setUserInput("");
  976. setPromptHints([]);
  977. if (!isMobileScreen) inputRef.current?.focus();
  978. setAutoScroll(true);
  979. };
  980. const onPromptSelect = (prompt: RenderPrompt) => {
  981. setTimeout(() => {
  982. setPromptHints([]);
  983. const matchedChatCommand = chatCommands.match(prompt.content);
  984. if (matchedChatCommand.matched) {
  985. // if user is selecting a chat command, just trigger it
  986. matchedChatCommand.invoke();
  987. setUserInput("");
  988. } else {
  989. // or fill the prompt
  990. setUserInput(prompt.content);
  991. }
  992. inputRef.current?.focus();
  993. }, 30);
  994. };
  995. // stop response
  996. const onUserStop = (messageId: string) => {
  997. ChatControllerPool.stop(session.id, messageId);
  998. };
  999. useEffect(() => {
  1000. chatStore.updateTargetSession(session, (session) => {
  1001. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  1002. session.messages.forEach((m) => {
  1003. // check if should stop all stale messages
  1004. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  1005. if (m.streaming) {
  1006. m.streaming = false;
  1007. }
  1008. if (m.content.length === 0) {
  1009. m.isError = true;
  1010. m.content = prettyObject({
  1011. error: true,
  1012. message: "empty response",
  1013. });
  1014. }
  1015. }
  1016. });
  1017. // auto sync mask config from global config
  1018. if (session.mask.syncGlobalConfig) {
  1019. console.log("[Mask] syncing from global, name = ", session.mask.name);
  1020. session.mask.modelConfig = { ...config.modelConfig };
  1021. }
  1022. });
  1023. // eslint-disable-next-line react-hooks/exhaustive-deps
  1024. }, [session]);
  1025. // check if should send message
  1026. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  1027. // if ArrowUp and no userInput, fill with last input
  1028. if (
  1029. e.key === "ArrowUp" &&
  1030. userInput.length <= 0 &&
  1031. !(e.metaKey || e.altKey || e.ctrlKey)
  1032. ) {
  1033. setUserInput(chatStore.lastInput ?? "");
  1034. e.preventDefault();
  1035. return;
  1036. }
  1037. if (shouldSubmit(e) && promptHints.length === 0) {
  1038. doSubmit(userInput);
  1039. e.preventDefault();
  1040. }
  1041. };
  1042. const onRightClick = (e: any, message: ChatMessage) => {
  1043. // copy to clipboard
  1044. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  1045. if (userInput.length === 0) {
  1046. setUserInput(getMessageTextContent(message));
  1047. }
  1048. e.preventDefault();
  1049. }
  1050. };
  1051. const deleteMessage = (msgId?: string) => {
  1052. chatStore.updateTargetSession(
  1053. session,
  1054. (session) =>
  1055. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  1056. );
  1057. };
  1058. const onDelete = (msgId: string) => {
  1059. deleteMessage(msgId);
  1060. };
  1061. const onResend = (message: ChatMessage) => {
  1062. // when it is resending a message
  1063. // 1. for a user's message, find the next bot response
  1064. // 2. for a bot's message, find the last user's input
  1065. // 3. delete original user input and bot's message
  1066. // 4. resend the user's input
  1067. const resendingIndex = session.messages.findIndex(
  1068. (m) => m.id === message.id,
  1069. );
  1070. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  1071. console.error("[Chat] failed to find resending message", message);
  1072. return;
  1073. }
  1074. let userMessage: ChatMessage | undefined;
  1075. let botMessage: ChatMessage | undefined;
  1076. if (message.role === "assistant") {
  1077. // if it is resending a bot's message, find the user input for it
  1078. botMessage = message;
  1079. for (let i = resendingIndex; i >= 0; i -= 1) {
  1080. if (session.messages[i].role === "user") {
  1081. userMessage = session.messages[i];
  1082. break;
  1083. }
  1084. }
  1085. } else if (message.role === "user") {
  1086. // if it is resending a user's input, find the bot's response
  1087. userMessage = message;
  1088. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  1089. if (session.messages[i].role === "assistant") {
  1090. botMessage = session.messages[i];
  1091. break;
  1092. }
  1093. }
  1094. }
  1095. if (userMessage === undefined) {
  1096. console.error("[Chat] failed to resend", message);
  1097. return;
  1098. }
  1099. // delete the original messages
  1100. deleteMessage(userMessage.id);
  1101. deleteMessage(botMessage?.id);
  1102. // resend the message
  1103. setIsLoading(true);
  1104. const textContent = getMessageTextContent(userMessage);
  1105. const images = getMessageImages(userMessage);
  1106. chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
  1107. inputRef.current?.focus();
  1108. };
  1109. const onPinMessage = (message: ChatMessage) => {
  1110. chatStore.updateTargetSession(session, (session) =>
  1111. session.mask.context.push(message),
  1112. );
  1113. showToast(Locale.Chat.Actions.PinToastContent, {
  1114. text: Locale.Chat.Actions.PinToastAction,
  1115. onClick: () => {
  1116. setShowPromptModal(true);
  1117. },
  1118. });
  1119. };
  1120. const accessStore = useAccessStore();
  1121. const [speechStatus, setSpeechStatus] = useState(false);
  1122. const [speechLoading, setSpeechLoading] = useState(false);
  1123. async function openaiSpeech(text: string) {
  1124. if (speechStatus) {
  1125. ttsPlayer.stop();
  1126. setSpeechStatus(false);
  1127. } else {
  1128. var api: ClientApi;
  1129. api = new ClientApi(ModelProvider.GPT);
  1130. const config = useAppConfig.getState();
  1131. setSpeechLoading(true);
  1132. ttsPlayer.init();
  1133. let audioBuffer: ArrayBuffer;
  1134. const { markdownToTxt } = require("markdown-to-txt");
  1135. const textContent = markdownToTxt(text);
  1136. if (config.ttsConfig.engine !== DEFAULT_TTS_ENGINE) {
  1137. const edgeVoiceName = accessStore.edgeVoiceName();
  1138. const tts = new MsEdgeTTS();
  1139. await tts.setMetadata(
  1140. edgeVoiceName,
  1141. OUTPUT_FORMAT.AUDIO_24KHZ_96KBITRATE_MONO_MP3,
  1142. );
  1143. audioBuffer = await tts.toArrayBuffer(textContent);
  1144. } else {
  1145. audioBuffer = await api.llm.speech({
  1146. model: config.ttsConfig.model,
  1147. input: textContent,
  1148. voice: config.ttsConfig.voice,
  1149. speed: config.ttsConfig.speed,
  1150. });
  1151. }
  1152. setSpeechStatus(true);
  1153. ttsPlayer
  1154. .play(audioBuffer, () => {
  1155. setSpeechStatus(false);
  1156. })
  1157. .catch((e) => {
  1158. console.error("[OpenAI Speech]", e);
  1159. showToast(prettyObject(e));
  1160. setSpeechStatus(false);
  1161. })
  1162. .finally(() => setSpeechLoading(false));
  1163. }
  1164. }
  1165. const context: RenderMessage[] = useMemo(() => {
  1166. return session.mask.hideContext ? [] : session.mask.context.slice();
  1167. }, [session.mask.context, session.mask.hideContext]);
  1168. if (
  1169. context.length === 0 &&
  1170. session.messages.at(0)?.content !== BOT_HELLO.content
  1171. ) {
  1172. const copiedHello = Object.assign({}, BOT_HELLO);
  1173. if (!accessStore.isAuthorized()) {
  1174. copiedHello.content = Locale.Error.Unauthorized;
  1175. }
  1176. context.push(copiedHello);
  1177. }
  1178. // preview messages
  1179. const renderMessages = useMemo(() => {
  1180. return context
  1181. .concat(session.messages as RenderMessage[])
  1182. .concat(
  1183. isLoading
  1184. ? [
  1185. {
  1186. ...createMessage({
  1187. role: "assistant",
  1188. content: "……",
  1189. }),
  1190. preview: true,
  1191. },
  1192. ]
  1193. : [],
  1194. )
  1195. .concat(
  1196. userInput.length > 0 && config.sendPreviewBubble
  1197. ? [
  1198. {
  1199. ...createMessage({
  1200. role: "user",
  1201. content: userInput,
  1202. }),
  1203. preview: true,
  1204. },
  1205. ]
  1206. : [],
  1207. );
  1208. }, [
  1209. config.sendPreviewBubble,
  1210. context,
  1211. isLoading,
  1212. session.messages,
  1213. userInput,
  1214. ]);
  1215. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  1216. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  1217. );
  1218. function setMsgRenderIndex(newIndex: number) {
  1219. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  1220. newIndex = Math.max(0, newIndex);
  1221. _setMsgRenderIndex(newIndex);
  1222. }
  1223. const messages = useMemo(() => {
  1224. const endRenderIndex = Math.min(
  1225. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  1226. renderMessages.length,
  1227. );
  1228. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  1229. }, [msgRenderIndex, renderMessages]);
  1230. const onChatBodyScroll = (e: HTMLElement) => {
  1231. const bottomHeight = e.scrollTop + e.clientHeight;
  1232. const edgeThreshold = e.clientHeight;
  1233. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  1234. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  1235. const isHitBottom =
  1236. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  1237. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  1238. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  1239. if (isTouchTopEdge && !isTouchBottomEdge) {
  1240. setMsgRenderIndex(prevPageMsgIndex);
  1241. } else if (isTouchBottomEdge) {
  1242. setMsgRenderIndex(nextPageMsgIndex);
  1243. }
  1244. setHitBottom(isHitBottom);
  1245. setAutoScroll(isHitBottom);
  1246. };
  1247. function scrollToBottom() {
  1248. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  1249. scrollDomToBottom();
  1250. }
  1251. // clear context index = context length + index in messages
  1252. const clearContextIndex =
  1253. (session.clearContextIndex ?? -1) >= 0
  1254. ? session.clearContextIndex! + context.length - msgRenderIndex
  1255. : -1;
  1256. const [showPromptModal, setShowPromptModal] = useState(false);
  1257. const clientConfig = useMemo(() => getClientConfig(), []);
  1258. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  1259. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  1260. useCommand({
  1261. fill: setUserInput,
  1262. submit: (text) => {
  1263. doSubmit(text);
  1264. },
  1265. code: (text) => {
  1266. if (accessStore.disableFastLink) return;
  1267. console.log("[Command] got code from url: ", text);
  1268. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  1269. if (res) {
  1270. accessStore.update((access) => (access.accessCode = text));
  1271. }
  1272. });
  1273. },
  1274. settings: (text) => {
  1275. if (accessStore.disableFastLink) return;
  1276. try {
  1277. const payload = JSON.parse(text) as {
  1278. key?: string;
  1279. url?: string;
  1280. };
  1281. console.log("[Command] got settings from url: ", payload);
  1282. if (payload.key || payload.url) {
  1283. showConfirm(
  1284. Locale.URLCommand.Settings +
  1285. `\n${JSON.stringify(payload, null, 4)}`,
  1286. ).then((res) => {
  1287. if (!res) return;
  1288. if (payload.key) {
  1289. accessStore.update(
  1290. (access) => (access.openaiApiKey = payload.key!),
  1291. );
  1292. }
  1293. if (payload.url) {
  1294. accessStore.update((access) => (access.openaiUrl = payload.url!));
  1295. }
  1296. accessStore.update((access) => (access.useCustomConfig = true));
  1297. });
  1298. }
  1299. } catch {
  1300. console.error("[Command] failed to get settings from url: ", text);
  1301. }
  1302. },
  1303. });
  1304. // edit / insert message modal
  1305. const [isEditingMessage, setIsEditingMessage] = useState(false);
  1306. // remember unfinished input
  1307. useEffect(() => {
  1308. // try to load from local storage
  1309. const key = UNFINISHED_INPUT(session.id);
  1310. const mayBeUnfinishedInput = localStorage.getItem(key);
  1311. if (mayBeUnfinishedInput && userInput.length === 0) {
  1312. setUserInput(mayBeUnfinishedInput);
  1313. localStorage.removeItem(key);
  1314. }
  1315. const dom = inputRef.current;
  1316. return () => {
  1317. localStorage.setItem(key, dom?.value ?? "");
  1318. };
  1319. // eslint-disable-next-line react-hooks/exhaustive-deps
  1320. }, []);
  1321. const handlePaste = useCallback(
  1322. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1323. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1324. if (!isVisionModel(currentModel)) {
  1325. return;
  1326. }
  1327. const items = (event.clipboardData || window.clipboardData).items;
  1328. for (const item of items) {
  1329. if (item.kind === "file" && item.type.startsWith("image/")) {
  1330. event.preventDefault();
  1331. const file = item.getAsFile();
  1332. if (file) {
  1333. const images: string[] = [];
  1334. images.push(...attachImages);
  1335. images.push(
  1336. ...(await new Promise<string[]>((res, rej) => {
  1337. setUploading(true);
  1338. const imagesData: string[] = [];
  1339. uploadImageRemote(file)
  1340. .then((dataUrl) => {
  1341. imagesData.push(dataUrl);
  1342. setUploading(false);
  1343. res(imagesData);
  1344. })
  1345. .catch((e) => {
  1346. setUploading(false);
  1347. rej(e);
  1348. });
  1349. })),
  1350. );
  1351. const imagesLength = images.length;
  1352. if (imagesLength > 3) {
  1353. images.splice(3, imagesLength - 3);
  1354. }
  1355. setAttachImages(images);
  1356. }
  1357. }
  1358. }
  1359. },
  1360. [attachImages, chatStore],
  1361. );
  1362. async function uploadImage() {
  1363. const images: string[] = [];
  1364. images.push(...attachImages);
  1365. images.push(
  1366. ...(await new Promise<string[]>((res, rej) => {
  1367. const fileInput = document.createElement("input");
  1368. fileInput.type = "file";
  1369. fileInput.accept =
  1370. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1371. fileInput.multiple = true;
  1372. fileInput.onchange = (event: any) => {
  1373. setUploading(true);
  1374. const files = event.target.files;
  1375. const imagesData: string[] = [];
  1376. for (let i = 0; i < files.length; i++) {
  1377. const file = event.target.files[i];
  1378. uploadImageRemote(file)
  1379. .then((dataUrl) => {
  1380. imagesData.push(dataUrl);
  1381. if (
  1382. imagesData.length === 3 ||
  1383. imagesData.length === files.length
  1384. ) {
  1385. setUploading(false);
  1386. res(imagesData);
  1387. }
  1388. })
  1389. .catch((e) => {
  1390. setUploading(false);
  1391. rej(e);
  1392. });
  1393. }
  1394. };
  1395. fileInput.click();
  1396. })),
  1397. );
  1398. const imagesLength = images.length;
  1399. if (imagesLength > 3) {
  1400. images.splice(3, imagesLength - 3);
  1401. }
  1402. setAttachImages(images);
  1403. }
  1404. // 快捷键 shortcut keys
  1405. const [showShortcutKeyModal, setShowShortcutKeyModal] = useState(false);
  1406. useEffect(() => {
  1407. const handleKeyDown = (event: any) => {
  1408. // 打开新聊天 command + shift + o
  1409. if (
  1410. (event.metaKey || event.ctrlKey) &&
  1411. event.shiftKey &&
  1412. event.key.toLowerCase() === "o"
  1413. ) {
  1414. event.preventDefault();
  1415. setTimeout(() => {
  1416. chatStore.newSession();
  1417. navigate(Path.Chat);
  1418. }, 10);
  1419. }
  1420. // 聚焦聊天输入 shift + esc
  1421. else if (event.shiftKey && event.key.toLowerCase() === "escape") {
  1422. event.preventDefault();
  1423. inputRef.current?.focus();
  1424. }
  1425. // 复制最后一个代码块 command + shift + ;
  1426. else if (
  1427. (event.metaKey || event.ctrlKey) &&
  1428. event.shiftKey &&
  1429. event.code === "Semicolon"
  1430. ) {
  1431. event.preventDefault();
  1432. const copyCodeButton =
  1433. document.querySelectorAll<HTMLElement>(".copy-code-button");
  1434. if (copyCodeButton.length > 0) {
  1435. copyCodeButton[copyCodeButton.length - 1].click();
  1436. }
  1437. }
  1438. // 复制最后一个回复 command + shift + c
  1439. else if (
  1440. (event.metaKey || event.ctrlKey) &&
  1441. event.shiftKey &&
  1442. event.key.toLowerCase() === "c"
  1443. ) {
  1444. event.preventDefault();
  1445. const lastNonUserMessage = messages
  1446. .filter((message) => message.role !== "user")
  1447. .pop();
  1448. if (lastNonUserMessage) {
  1449. const lastMessageContent = getMessageTextContent(lastNonUserMessage);
  1450. copyToClipboard(lastMessageContent);
  1451. }
  1452. }
  1453. // 展示快捷键 command + /
  1454. else if ((event.metaKey || event.ctrlKey) && event.key === "/") {
  1455. event.preventDefault();
  1456. setShowShortcutKeyModal(true);
  1457. }
  1458. };
  1459. window.addEventListener("keydown", handleKeyDown);
  1460. return () => {
  1461. window.removeEventListener("keydown", handleKeyDown);
  1462. };
  1463. }, [messages, chatStore, navigate]);
  1464. const [showChatSidePanel, setShowChatSidePanel] = useState(false);
  1465. return (
  1466. <>
  1467. <div className={styles.chat} key={session.id}>
  1468. <div className="window-header" data-tauri-drag-region>
  1469. {isMobileScreen && (
  1470. <div className="window-actions">
  1471. <div className={"window-action-button"}>
  1472. <IconButton
  1473. icon={<ReturnIcon />}
  1474. bordered
  1475. title={Locale.Chat.Actions.ChatList}
  1476. onClick={() => navigate(Path.Home)}
  1477. />
  1478. </div>
  1479. </div>
  1480. )}
  1481. <div
  1482. className={clsx("window-header-title", styles["chat-body-title"])}
  1483. >
  1484. <div
  1485. className={clsx(
  1486. "window-header-main-title",
  1487. styles["chat-body-main-title"],
  1488. )}
  1489. onClickCapture={() => setIsEditingMessage(true)}
  1490. >
  1491. {!session.topic ? DEFAULT_TOPIC : session.topic}
  1492. </div>
  1493. <div className="window-header-sub-title">
  1494. {Locale.Chat.SubTitle(session.messages.length)}
  1495. </div>
  1496. </div>
  1497. <div className="window-actions">
  1498. <div className="window-action-button">
  1499. <IconButton
  1500. icon={<ReloadIcon />}
  1501. bordered
  1502. title={Locale.Chat.Actions.RefreshTitle}
  1503. onClick={() => {
  1504. showToast(Locale.Chat.Actions.RefreshToast);
  1505. chatStore.summarizeSession(true, session);
  1506. }}
  1507. />
  1508. </div>
  1509. {!isMobileScreen && (
  1510. <div className="window-action-button">
  1511. <IconButton
  1512. icon={<RenameIcon />}
  1513. bordered
  1514. title={Locale.Chat.EditMessage.Title}
  1515. aria={Locale.Chat.EditMessage.Title}
  1516. onClick={() => setIsEditingMessage(true)}
  1517. />
  1518. </div>
  1519. )}
  1520. <div className="window-action-button">
  1521. <IconButton
  1522. icon={<ExportIcon />}
  1523. bordered
  1524. title={Locale.Chat.Actions.Export}
  1525. onClick={() => {
  1526. setShowExport(true);
  1527. }}
  1528. />
  1529. </div>
  1530. {showMaxIcon && (
  1531. <div className="window-action-button">
  1532. <IconButton
  1533. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1534. bordered
  1535. title={Locale.Chat.Actions.FullScreen}
  1536. aria={Locale.Chat.Actions.FullScreen}
  1537. onClick={() => {
  1538. config.update(
  1539. (config) => (config.tightBorder = !config.tightBorder),
  1540. );
  1541. }}
  1542. />
  1543. </div>
  1544. )}
  1545. </div>
  1546. <PromptToast
  1547. showToast={!hitBottom}
  1548. showModal={showPromptModal}
  1549. setShowModal={setShowPromptModal}
  1550. />
  1551. </div>
  1552. <div className={styles["chat-main"]}>
  1553. <div className={styles["chat-body-container"]}>
  1554. <div
  1555. className={styles["chat-body"]}
  1556. ref={scrollRef}
  1557. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1558. onMouseDown={() => inputRef.current?.blur()}
  1559. onTouchStart={() => {
  1560. inputRef.current?.blur();
  1561. setAutoScroll(false);
  1562. }}
  1563. >
  1564. {messages.map((message, i) => {
  1565. const isUser = message.role === "user";
  1566. const isContext = i < context.length;
  1567. const showActions =
  1568. i > 0 &&
  1569. !(message.preview || message.content.length === 0) &&
  1570. !isContext;
  1571. const showTyping = message.preview || message.streaming;
  1572. const shouldShowClearContextDivider =
  1573. i === clearContextIndex - 1;
  1574. return (
  1575. <Fragment key={message.id}>
  1576. <div
  1577. className={
  1578. isUser
  1579. ? styles["chat-message-user"]
  1580. : styles["chat-message"]
  1581. }
  1582. >
  1583. <div className={styles["chat-message-container"]}>
  1584. <div className={styles["chat-message-header"]}>
  1585. <div className={styles["chat-message-avatar"]}>
  1586. <div className={styles["chat-message-edit"]}>
  1587. <IconButton
  1588. icon={<EditIcon />}
  1589. aria={Locale.Chat.Actions.Edit}
  1590. onClick={async () => {
  1591. const newMessage = await showPrompt(
  1592. Locale.Chat.Actions.Edit,
  1593. getMessageTextContent(message),
  1594. 10,
  1595. );
  1596. let newContent: string | MultimodalContent[] =
  1597. newMessage;
  1598. const images = getMessageImages(message);
  1599. if (images.length > 0) {
  1600. newContent = [
  1601. { type: "text", text: newMessage },
  1602. ];
  1603. for (let i = 0; i < images.length; i++) {
  1604. newContent.push({
  1605. type: "image_url",
  1606. image_url: {
  1607. url: images[i],
  1608. },
  1609. });
  1610. }
  1611. }
  1612. chatStore.updateTargetSession(
  1613. session,
  1614. (session) => {
  1615. const m = session.mask.context
  1616. .concat(session.messages)
  1617. .find((m) => m.id === message.id);
  1618. if (m) {
  1619. m.content = newContent;
  1620. }
  1621. },
  1622. );
  1623. }}
  1624. ></IconButton>
  1625. </div>
  1626. {isUser ? (
  1627. <Avatar avatar={config.avatar} />
  1628. ) : (
  1629. <>
  1630. {["system"].includes(message.role) ? (
  1631. <Avatar avatar="2699-fe0f" />
  1632. ) : (
  1633. <MaskAvatar
  1634. avatar={session.mask.avatar}
  1635. model={
  1636. message.model ||
  1637. session.mask.modelConfig.model
  1638. }
  1639. />
  1640. )}
  1641. </>
  1642. )}
  1643. </div>
  1644. {!isUser && (
  1645. <div className={styles["chat-model-name"]}>
  1646. {message.model}
  1647. </div>
  1648. )}
  1649. {showActions && (
  1650. <div className={styles["chat-message-actions"]}>
  1651. <div className={styles["chat-input-actions"]}>
  1652. {message.streaming ? (
  1653. <ChatAction
  1654. text={Locale.Chat.Actions.Stop}
  1655. icon={<StopIcon />}
  1656. onClick={() => onUserStop(message.id ?? i)}
  1657. />
  1658. ) : (
  1659. <>
  1660. <ChatAction
  1661. text={Locale.Chat.Actions.Retry}
  1662. icon={<ResetIcon />}
  1663. onClick={() => onResend(message)}
  1664. />
  1665. <ChatAction
  1666. text={Locale.Chat.Actions.Delete}
  1667. icon={<DeleteIcon />}
  1668. onClick={() => onDelete(message.id ?? i)}
  1669. />
  1670. <ChatAction
  1671. text={Locale.Chat.Actions.Pin}
  1672. icon={<PinIcon />}
  1673. onClick={() => onPinMessage(message)}
  1674. />
  1675. <ChatAction
  1676. text={Locale.Chat.Actions.Copy}
  1677. icon={<CopyIcon />}
  1678. onClick={() =>
  1679. copyToClipboard(
  1680. getMessageTextContent(message),
  1681. )
  1682. }
  1683. />
  1684. {config.ttsConfig.enable && (
  1685. <ChatAction
  1686. text={
  1687. speechStatus
  1688. ? Locale.Chat.Actions.StopSpeech
  1689. : Locale.Chat.Actions.Speech
  1690. }
  1691. icon={
  1692. speechStatus ? (
  1693. <SpeakStopIcon />
  1694. ) : (
  1695. <SpeakIcon />
  1696. )
  1697. }
  1698. onClick={() =>
  1699. openaiSpeech(
  1700. getMessageTextContent(message),
  1701. )
  1702. }
  1703. />
  1704. )}
  1705. </>
  1706. )}
  1707. </div>
  1708. </div>
  1709. )}
  1710. </div>
  1711. {message?.tools?.length == 0 && showTyping && (
  1712. <div className={styles["chat-message-status"]}>
  1713. {Locale.Chat.Typing}
  1714. </div>
  1715. )}
  1716. {/*@ts-ignore*/}
  1717. {message?.tools?.length > 0 && (
  1718. <div className={styles["chat-message-tools"]}>
  1719. {message?.tools?.map((tool) => (
  1720. <div
  1721. key={tool.id}
  1722. title={tool?.errorMsg}
  1723. className={styles["chat-message-tool"]}
  1724. >
  1725. {tool.isError === false ? (
  1726. <ConfirmIcon />
  1727. ) : tool.isError === true ? (
  1728. <CloseIcon />
  1729. ) : (
  1730. <LoadingButtonIcon />
  1731. )}
  1732. <span>{tool?.function?.name}</span>
  1733. </div>
  1734. ))}
  1735. </div>
  1736. )}
  1737. <div className={styles["chat-message-item"]}>
  1738. <Markdown
  1739. key={message.streaming ? "loading" : "done"}
  1740. content={getMessageTextContent(message)}
  1741. loading={
  1742. (message.preview || message.streaming) &&
  1743. message.content.length === 0 &&
  1744. !isUser
  1745. }
  1746. // onContextMenu={(e) => onRightClick(e, message)} // hard to use
  1747. onDoubleClickCapture={() => {
  1748. if (!isMobileScreen) return;
  1749. setUserInput(getMessageTextContent(message));
  1750. }}
  1751. fontSize={fontSize}
  1752. fontFamily={fontFamily}
  1753. parentRef={scrollRef}
  1754. defaultShow={i >= messages.length - 6}
  1755. />
  1756. {getMessageImages(message).length == 1 && (
  1757. <img
  1758. className={styles["chat-message-item-image"]}
  1759. src={getMessageImages(message)[0]}
  1760. alt=""
  1761. />
  1762. )}
  1763. {getMessageImages(message).length > 1 && (
  1764. <div
  1765. className={styles["chat-message-item-images"]}
  1766. style={
  1767. {
  1768. "--image-count":
  1769. getMessageImages(message).length,
  1770. } as React.CSSProperties
  1771. }
  1772. >
  1773. {getMessageImages(message).map((image, index) => {
  1774. return (
  1775. <img
  1776. className={
  1777. styles["chat-message-item-image-multi"]
  1778. }
  1779. key={index}
  1780. src={image}
  1781. alt=""
  1782. />
  1783. );
  1784. })}
  1785. </div>
  1786. )}
  1787. </div>
  1788. {message?.audio_url && (
  1789. <div className={styles["chat-message-audio"]}>
  1790. <audio src={message.audio_url} controls />
  1791. </div>
  1792. )}
  1793. <div className={styles["chat-message-action-date"]}>
  1794. {isContext
  1795. ? Locale.Chat.IsContext
  1796. : message.date.toLocaleString()}
  1797. </div>
  1798. </div>
  1799. </div>
  1800. {shouldShowClearContextDivider && <ClearContextDivider />}
  1801. </Fragment>
  1802. );
  1803. })}
  1804. </div>
  1805. <div className={styles["chat-input-panel"]}>
  1806. <PromptHints
  1807. prompts={promptHints}
  1808. onPromptSelect={onPromptSelect}
  1809. />
  1810. <ChatActions
  1811. uploadImage={uploadImage}
  1812. setAttachImages={setAttachImages}
  1813. setUploading={setUploading}
  1814. showPromptModal={() => setShowPromptModal(true)}
  1815. scrollToBottom={scrollToBottom}
  1816. hitBottom={hitBottom}
  1817. uploading={uploading}
  1818. showPromptHints={() => {
  1819. // Click again to close
  1820. if (promptHints.length > 0) {
  1821. setPromptHints([]);
  1822. return;
  1823. }
  1824. inputRef.current?.focus();
  1825. setUserInput("/");
  1826. onSearch("");
  1827. }}
  1828. setShowShortcutKeyModal={setShowShortcutKeyModal}
  1829. setUserInput={setUserInput}
  1830. setShowChatSidePanel={setShowChatSidePanel}
  1831. />
  1832. <label
  1833. className={clsx(styles["chat-input-panel-inner"], {
  1834. [styles["chat-input-panel-inner-attach"]]:
  1835. attachImages.length !== 0,
  1836. })}
  1837. htmlFor="chat-input"
  1838. >
  1839. <textarea
  1840. id="chat-input"
  1841. ref={inputRef}
  1842. className={styles["chat-input"]}
  1843. placeholder={Locale.Chat.Input(submitKey)}
  1844. onInput={(e) => onInput(e.currentTarget.value)}
  1845. value={userInput}
  1846. onKeyDown={onInputKeyDown}
  1847. onFocus={scrollToBottom}
  1848. onClick={scrollToBottom}
  1849. onPaste={handlePaste}
  1850. rows={inputRows}
  1851. autoFocus={autoFocus}
  1852. style={{
  1853. fontSize: config.fontSize,
  1854. fontFamily: config.fontFamily,
  1855. }}
  1856. />
  1857. {attachImages.length != 0 && (
  1858. <div className={styles["attach-images"]}>
  1859. {attachImages.map((image, index) => {
  1860. return (
  1861. <div
  1862. key={index}
  1863. className={styles["attach-image"]}
  1864. style={{ backgroundImage: `url("${image}")` }}
  1865. >
  1866. <div className={styles["attach-image-mask"]}>
  1867. <DeleteImageButton
  1868. deleteImage={() => {
  1869. setAttachImages(
  1870. attachImages.filter((_, i) => i !== index),
  1871. );
  1872. }}
  1873. />
  1874. </div>
  1875. </div>
  1876. );
  1877. })}
  1878. </div>
  1879. )}
  1880. <IconButton
  1881. icon={<SendWhiteIcon />}
  1882. text={Locale.Chat.Send}
  1883. className={styles["chat-input-send"]}
  1884. type="primary"
  1885. onClick={() => doSubmit(userInput)}
  1886. />
  1887. </label>
  1888. </div>
  1889. </div>
  1890. <div
  1891. className={clsx(styles["chat-side-panel"], {
  1892. [styles["mobile"]]: isMobileScreen,
  1893. [styles["chat-side-panel-show"]]: showChatSidePanel,
  1894. })}
  1895. >
  1896. <RealtimeChat
  1897. onClose={() => {
  1898. setShowChatSidePanel(false);
  1899. }}
  1900. onStartVoice={async () => {
  1901. console.log("start voice");
  1902. }}
  1903. />
  1904. </div>
  1905. </div>
  1906. </div>
  1907. {showExport && (
  1908. <ExportMessageModal onClose={() => setShowExport(false)} />
  1909. )}
  1910. {isEditingMessage && (
  1911. <EditMessageModal
  1912. onClose={() => {
  1913. setIsEditingMessage(false);
  1914. }}
  1915. />
  1916. )}
  1917. {showShortcutKeyModal && (
  1918. <ShortcutKeyModal onClose={() => setShowShortcutKeyModal(false)} />
  1919. )}
  1920. </>
  1921. );
  1922. }
  1923. export function Chat() {
  1924. const chatStore = useChatStore();
  1925. const sessionIndex = chatStore.currentSessionIndex;
  1926. return <_Chat key={sessionIndex}></_Chat>;
  1927. }