chat.tsx 68 KB

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