chat.tsx 68 KB

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