chat.tsx 67 KB

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