chat.tsx 69 KB

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