chat.tsx 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. import { useDebouncedCallback } from "use-debounce";
  2. import React, {
  3. useState,
  4. useRef,
  5. useEffect,
  6. useMemo,
  7. useCallback,
  8. Fragment,
  9. } from "react";
  10. import SendWhiteIcon from "../icons/send-white.svg";
  11. import BrainIcon from "../icons/brain.svg";
  12. import RenameIcon from "../icons/rename.svg";
  13. import ExportIcon from "../icons/share.svg";
  14. import ReturnIcon from "../icons/return.svg";
  15. import CopyIcon from "../icons/copy.svg";
  16. import LoadingIcon from "../icons/three-dots.svg";
  17. import LoadingButtonIcon from "../icons/loading.svg";
  18. import PromptIcon from "../icons/prompt.svg";
  19. import MaskIcon from "../icons/mask.svg";
  20. import MaxIcon from "../icons/max.svg";
  21. import MinIcon from "../icons/min.svg";
  22. import ResetIcon from "../icons/reload.svg";
  23. import BreakIcon from "../icons/break.svg";
  24. import SettingsIcon from "../icons/chat-settings.svg";
  25. import DeleteIcon from "../icons/clear.svg";
  26. import PinIcon from "../icons/pin.svg";
  27. import EditIcon from "../icons/rename.svg";
  28. import ConfirmIcon from "../icons/confirm.svg";
  29. import CancelIcon from "../icons/cancel.svg";
  30. import ImageIcon from "../icons/image.svg";
  31. import LightIcon from "../icons/light.svg";
  32. import DarkIcon from "../icons/dark.svg";
  33. import AutoIcon from "../icons/auto.svg";
  34. import BottomIcon from "../icons/bottom.svg";
  35. import StopIcon from "../icons/pause.svg";
  36. import RobotIcon from "../icons/robot.svg";
  37. import {
  38. ChatMessage,
  39. SubmitKey,
  40. useChatStore,
  41. BOT_HELLO,
  42. createMessage,
  43. useAccessStore,
  44. Theme,
  45. useAppConfig,
  46. DEFAULT_TOPIC,
  47. ModelType,
  48. } from "../store";
  49. import {
  50. copyToClipboard,
  51. selectOrCopy,
  52. autoGrowTextArea,
  53. useMobileScreen,
  54. getMessageTextContent,
  55. getMessageImages,
  56. isVisionModel,
  57. compressImage,
  58. } from "../utils";
  59. import dynamic from "next/dynamic";
  60. import { ChatControllerPool } from "../client/controller";
  61. import { Prompt, usePromptStore } from "../store/prompt";
  62. import Locale from "../locales";
  63. import { IconButton } from "./button";
  64. import styles from "./chat.module.scss";
  65. import {
  66. List,
  67. ListItem,
  68. Modal,
  69. Selector,
  70. showConfirm,
  71. showPrompt,
  72. showToast,
  73. } from "./ui-lib";
  74. import { useNavigate } from "react-router-dom";
  75. import {
  76. CHAT_PAGE_SIZE,
  77. LAST_INPUT_KEY,
  78. Path,
  79. REQUEST_TIMEOUT_MS,
  80. UNFINISHED_INPUT,
  81. } from "../constant";
  82. import { Avatar } from "./emoji";
  83. import { ContextPrompts, MaskAvatar, MaskConfig } from "./mask";
  84. import { useMaskStore } from "../store/mask";
  85. import { ChatCommandPrefix, useChatCommand, useCommand } from "../command";
  86. import { prettyObject } from "../utils/format";
  87. import { ExportMessageModal } from "./exporter";
  88. import { getClientConfig } from "../config/client";
  89. import { useAllModels } from "../utils/hooks";
  90. import { MultimodalContent } from "../client/api";
  91. const Markdown = dynamic(async () => (await import("./markdown")).Markdown, {
  92. loading: () => <LoadingIcon />,
  93. });
  94. export function SessionConfigModel(props: { onClose: () => void }) {
  95. const chatStore = useChatStore();
  96. const session = chatStore.currentSession();
  97. const maskStore = useMaskStore();
  98. const navigate = useNavigate();
  99. return (
  100. <div className="modal-mask">
  101. <Modal
  102. title={Locale.Context.Edit}
  103. onClose={() => props.onClose()}
  104. actions={[
  105. <IconButton
  106. key="reset"
  107. icon={<ResetIcon />}
  108. bordered
  109. text={Locale.Chat.Config.Reset}
  110. onClick={async () => {
  111. if (await showConfirm(Locale.Memory.ResetConfirm)) {
  112. chatStore.updateCurrentSession(
  113. (session) => (session.memoryPrompt = ""),
  114. );
  115. }
  116. }}
  117. />,
  118. <IconButton
  119. key="copy"
  120. icon={<CopyIcon />}
  121. bordered
  122. text={Locale.Chat.Config.SaveAs}
  123. onClick={() => {
  124. navigate(Path.Masks);
  125. setTimeout(() => {
  126. maskStore.create(session.mask);
  127. }, 500);
  128. }}
  129. />,
  130. ]}
  131. >
  132. <MaskConfig
  133. mask={session.mask}
  134. updateMask={(updater) => {
  135. const mask = { ...session.mask };
  136. updater(mask);
  137. chatStore.updateCurrentSession((session) => (session.mask = mask));
  138. }}
  139. shouldSyncFromGlobal
  140. extraListItems={
  141. session.mask.modelConfig.sendMemory ? (
  142. <ListItem
  143. className="copyable"
  144. title={`${Locale.Memory.Title} (${session.lastSummarizeIndex} of ${session.messages.length})`}
  145. subTitle={session.memoryPrompt || Locale.Memory.EmptyContent}
  146. ></ListItem>
  147. ) : (
  148. <></>
  149. )
  150. }
  151. ></MaskConfig>
  152. </Modal>
  153. </div>
  154. );
  155. }
  156. function PromptToast(props: {
  157. showToast?: boolean;
  158. showModal?: boolean;
  159. setShowModal: (_: boolean) => void;
  160. }) {
  161. const chatStore = useChatStore();
  162. const session = chatStore.currentSession();
  163. const context = session.mask.context;
  164. return (
  165. <div className={styles["prompt-toast"]} key="prompt-toast">
  166. {props.showToast && (
  167. <div
  168. className={styles["prompt-toast-inner"] + " clickable"}
  169. role="button"
  170. onClick={() => props.setShowModal(true)}
  171. >
  172. <BrainIcon />
  173. <span className={styles["prompt-toast-content"]}>
  174. {Locale.Context.Toast(context.length)}
  175. </span>
  176. </div>
  177. )}
  178. {props.showModal && (
  179. <SessionConfigModel onClose={() => props.setShowModal(false)} />
  180. )}
  181. </div>
  182. );
  183. }
  184. function useSubmitHandler() {
  185. const config = useAppConfig();
  186. const submitKey = config.submitKey;
  187. const isComposing = useRef(false);
  188. useEffect(() => {
  189. const onCompositionStart = () => {
  190. isComposing.current = true;
  191. };
  192. const onCompositionEnd = () => {
  193. isComposing.current = false;
  194. };
  195. window.addEventListener("compositionstart", onCompositionStart);
  196. window.addEventListener("compositionend", onCompositionEnd);
  197. return () => {
  198. window.removeEventListener("compositionstart", onCompositionStart);
  199. window.removeEventListener("compositionend", onCompositionEnd);
  200. };
  201. }, []);
  202. const shouldSubmit = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  203. if (e.key !== "Enter") return false;
  204. if (e.key === "Enter" && (e.nativeEvent.isComposing || isComposing.current))
  205. return false;
  206. return (
  207. (config.submitKey === SubmitKey.AltEnter && e.altKey) ||
  208. (config.submitKey === SubmitKey.CtrlEnter && e.ctrlKey) ||
  209. (config.submitKey === SubmitKey.ShiftEnter && e.shiftKey) ||
  210. (config.submitKey === SubmitKey.MetaEnter && e.metaKey) ||
  211. (config.submitKey === SubmitKey.Enter &&
  212. !e.altKey &&
  213. !e.ctrlKey &&
  214. !e.shiftKey &&
  215. !e.metaKey)
  216. );
  217. };
  218. return {
  219. submitKey,
  220. shouldSubmit,
  221. };
  222. }
  223. export type RenderPompt = Pick<Prompt, "title" | "content">;
  224. export function PromptHints(props: {
  225. prompts: RenderPompt[];
  226. onPromptSelect: (prompt: RenderPompt) => void;
  227. }) {
  228. const noPrompts = props.prompts.length === 0;
  229. const [selectIndex, setSelectIndex] = useState(0);
  230. const selectedRef = useRef<HTMLDivElement>(null);
  231. useEffect(() => {
  232. setSelectIndex(0);
  233. }, [props.prompts.length]);
  234. useEffect(() => {
  235. const onKeyDown = (e: KeyboardEvent) => {
  236. if (noPrompts || e.metaKey || e.altKey || e.ctrlKey) {
  237. return;
  238. }
  239. // arrow up / down to select prompt
  240. const changeIndex = (delta: number) => {
  241. e.stopPropagation();
  242. e.preventDefault();
  243. const nextIndex = Math.max(
  244. 0,
  245. Math.min(props.prompts.length - 1, selectIndex + delta),
  246. );
  247. setSelectIndex(nextIndex);
  248. selectedRef.current?.scrollIntoView({
  249. block: "center",
  250. });
  251. };
  252. if (e.key === "ArrowUp") {
  253. changeIndex(1);
  254. } else if (e.key === "ArrowDown") {
  255. changeIndex(-1);
  256. } else if (e.key === "Enter") {
  257. const selectedPrompt = props.prompts.at(selectIndex);
  258. if (selectedPrompt) {
  259. props.onPromptSelect(selectedPrompt);
  260. }
  261. }
  262. };
  263. window.addEventListener("keydown", onKeyDown);
  264. return () => window.removeEventListener("keydown", onKeyDown);
  265. // eslint-disable-next-line react-hooks/exhaustive-deps
  266. }, [props.prompts.length, selectIndex]);
  267. if (noPrompts) return null;
  268. return (
  269. <div className={styles["prompt-hints"]}>
  270. {props.prompts.map((prompt, i) => (
  271. <div
  272. ref={i === selectIndex ? selectedRef : null}
  273. className={
  274. styles["prompt-hint"] +
  275. ` ${i === selectIndex ? styles["prompt-hint-selected"] : ""}`
  276. }
  277. key={prompt.title + i.toString()}
  278. onClick={() => props.onPromptSelect(prompt)}
  279. onMouseEnter={() => setSelectIndex(i)}
  280. >
  281. <div className={styles["hint-title"]}>{prompt.title}</div>
  282. <div className={styles["hint-content"]}>{prompt.content}</div>
  283. </div>
  284. ))}
  285. </div>
  286. );
  287. }
  288. function ClearContextDivider() {
  289. const chatStore = useChatStore();
  290. return (
  291. <div
  292. className={styles["clear-context"]}
  293. onClick={() =>
  294. chatStore.updateCurrentSession(
  295. (session) => (session.clearContextIndex = undefined),
  296. )
  297. }
  298. >
  299. <div className={styles["clear-context-tips"]}>{Locale.Context.Clear}</div>
  300. <div className={styles["clear-context-revert-btn"]}>
  301. {Locale.Context.Revert}
  302. </div>
  303. </div>
  304. );
  305. }
  306. function ChatAction(props: {
  307. text: string;
  308. icon: JSX.Element;
  309. onClick: () => void;
  310. }) {
  311. const iconRef = useRef<HTMLDivElement>(null);
  312. const textRef = useRef<HTMLDivElement>(null);
  313. const [width, setWidth] = useState({
  314. full: 16,
  315. icon: 16,
  316. });
  317. function updateWidth() {
  318. if (!iconRef.current || !textRef.current) return;
  319. const getWidth = (dom: HTMLDivElement) => dom.getBoundingClientRect().width;
  320. const textWidth = getWidth(textRef.current);
  321. const iconWidth = getWidth(iconRef.current);
  322. setWidth({
  323. full: textWidth + iconWidth,
  324. icon: iconWidth,
  325. });
  326. }
  327. return (
  328. <div
  329. className={`${styles["chat-input-action"]} clickable`}
  330. onClick={() => {
  331. props.onClick();
  332. setTimeout(updateWidth, 1);
  333. }}
  334. onMouseEnter={updateWidth}
  335. onTouchStart={updateWidth}
  336. style={
  337. {
  338. "--icon-width": `${width.icon}px`,
  339. "--full-width": `${width.full}px`,
  340. } as React.CSSProperties
  341. }
  342. >
  343. <div ref={iconRef} className={styles["icon"]}>
  344. {props.icon}
  345. </div>
  346. <div className={styles["text"]} ref={textRef}>
  347. {props.text}
  348. </div>
  349. </div>
  350. );
  351. }
  352. function useScrollToBottom() {
  353. // for auto-scroll
  354. const scrollRef = useRef<HTMLDivElement>(null);
  355. const [autoScroll, setAutoScroll] = useState(true);
  356. function scrollDomToBottom() {
  357. const dom = scrollRef.current;
  358. if (dom) {
  359. requestAnimationFrame(() => {
  360. setAutoScroll(true);
  361. dom.scrollTo(0, dom.scrollHeight);
  362. });
  363. }
  364. }
  365. // auto scroll
  366. useEffect(() => {
  367. if (autoScroll) {
  368. scrollDomToBottom();
  369. }
  370. });
  371. return {
  372. scrollRef,
  373. autoScroll,
  374. setAutoScroll,
  375. scrollDomToBottom,
  376. };
  377. }
  378. export function ChatActions(props: {
  379. uploadImage: () => void;
  380. setAttachImages: (images: string[]) => void;
  381. setUploading: (uploading: boolean) => void;
  382. showPromptModal: () => void;
  383. scrollToBottom: () => void;
  384. showPromptHints: () => void;
  385. hitBottom: boolean;
  386. uploading: boolean;
  387. }) {
  388. const config = useAppConfig();
  389. const navigate = useNavigate();
  390. const chatStore = useChatStore();
  391. // switch themes
  392. const theme = config.theme;
  393. function nextTheme() {
  394. const themes = [Theme.Auto, Theme.Light, Theme.Dark];
  395. const themeIndex = themes.indexOf(theme);
  396. const nextIndex = (themeIndex + 1) % themes.length;
  397. const nextTheme = themes[nextIndex];
  398. config.update((config) => (config.theme = nextTheme));
  399. }
  400. // stop all responses
  401. const couldStop = ChatControllerPool.hasPending();
  402. const stopAll = () => ChatControllerPool.stopAll();
  403. // switch model
  404. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  405. const allModels = useAllModels();
  406. const models = useMemo(
  407. () => allModels.filter((m) => m.available),
  408. [allModels],
  409. );
  410. const [showModelSelector, setShowModelSelector] = useState(false);
  411. const [showUploadImage, setShowUploadImage] = useState(false);
  412. useEffect(() => {
  413. const show = isVisionModel(currentModel);
  414. setShowUploadImage(show);
  415. if (!show) {
  416. props.setAttachImages([]);
  417. props.setUploading(false);
  418. }
  419. // if current model is not available
  420. // switch to first available model
  421. const isUnavaliableModel = !models.some((m) => m.name === currentModel);
  422. if (isUnavaliableModel && models.length > 0) {
  423. const nextModel = models[0].name as ModelType;
  424. chatStore.updateCurrentSession(
  425. (session) => (session.mask.modelConfig.model = nextModel),
  426. );
  427. showToast(nextModel);
  428. }
  429. }, [chatStore, currentModel, models]);
  430. return (
  431. <div className={styles["chat-input-actions"]}>
  432. {couldStop && (
  433. <ChatAction
  434. onClick={stopAll}
  435. text={Locale.Chat.InputActions.Stop}
  436. icon={<StopIcon />}
  437. />
  438. )}
  439. {!props.hitBottom && (
  440. <ChatAction
  441. onClick={props.scrollToBottom}
  442. text={Locale.Chat.InputActions.ToBottom}
  443. icon={<BottomIcon />}
  444. />
  445. )}
  446. {props.hitBottom && (
  447. <ChatAction
  448. onClick={props.showPromptModal}
  449. text={Locale.Chat.InputActions.Settings}
  450. icon={<SettingsIcon />}
  451. />
  452. )}
  453. {showUploadImage && (
  454. <ChatAction
  455. onClick={props.uploadImage}
  456. text={Locale.Chat.InputActions.UploadImage}
  457. icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
  458. />
  459. )}
  460. <ChatAction
  461. onClick={nextTheme}
  462. text={Locale.Chat.InputActions.Theme[theme]}
  463. icon={
  464. <>
  465. {theme === Theme.Auto ? (
  466. <AutoIcon />
  467. ) : theme === Theme.Light ? (
  468. <LightIcon />
  469. ) : theme === Theme.Dark ? (
  470. <DarkIcon />
  471. ) : null}
  472. </>
  473. }
  474. />
  475. <ChatAction
  476. onClick={props.showPromptHints}
  477. text={Locale.Chat.InputActions.Prompt}
  478. icon={<PromptIcon />}
  479. />
  480. <ChatAction
  481. onClick={() => {
  482. navigate(Path.Masks);
  483. }}
  484. text={Locale.Chat.InputActions.Masks}
  485. icon={<MaskIcon />}
  486. />
  487. <ChatAction
  488. text={Locale.Chat.InputActions.Clear}
  489. icon={<BreakIcon />}
  490. onClick={() => {
  491. chatStore.updateCurrentSession((session) => {
  492. if (session.clearContextIndex === session.messages.length) {
  493. session.clearContextIndex = undefined;
  494. } else {
  495. session.clearContextIndex = session.messages.length;
  496. session.memoryPrompt = ""; // will clear memory
  497. }
  498. });
  499. }}
  500. />
  501. <ChatAction
  502. onClick={() => setShowModelSelector(true)}
  503. text={currentModel}
  504. icon={<RobotIcon />}
  505. />
  506. {showModelSelector && (
  507. <Selector
  508. defaultSelectedValue={currentModel}
  509. items={models.map((m) => ({
  510. title: m.displayName,
  511. value: m.name,
  512. }))}
  513. onClose={() => setShowModelSelector(false)}
  514. onSelection={(s) => {
  515. if (s.length === 0) return;
  516. chatStore.updateCurrentSession((session) => {
  517. session.mask.modelConfig.model = s[0] as ModelType;
  518. session.mask.syncGlobalConfig = false;
  519. });
  520. showToast(s[0]);
  521. }}
  522. />
  523. )}
  524. </div>
  525. );
  526. }
  527. export function EditMessageModal(props: { onClose: () => void }) {
  528. const chatStore = useChatStore();
  529. const session = chatStore.currentSession();
  530. const [messages, setMessages] = useState(session.messages.slice());
  531. return (
  532. <div className="modal-mask">
  533. <Modal
  534. title={Locale.Chat.EditMessage.Title}
  535. onClose={props.onClose}
  536. actions={[
  537. <IconButton
  538. text={Locale.UI.Cancel}
  539. icon={<CancelIcon />}
  540. key="cancel"
  541. onClick={() => {
  542. props.onClose();
  543. }}
  544. />,
  545. <IconButton
  546. type="primary"
  547. text={Locale.UI.Confirm}
  548. icon={<ConfirmIcon />}
  549. key="ok"
  550. onClick={() => {
  551. chatStore.updateCurrentSession(
  552. (session) => (session.messages = messages),
  553. );
  554. props.onClose();
  555. }}
  556. />,
  557. ]}
  558. >
  559. <List>
  560. <ListItem
  561. title={Locale.Chat.EditMessage.Topic.Title}
  562. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  563. >
  564. <input
  565. type="text"
  566. value={session.topic}
  567. onInput={(e) =>
  568. chatStore.updateCurrentSession(
  569. (session) => (session.topic = e.currentTarget.value),
  570. )
  571. }
  572. ></input>
  573. </ListItem>
  574. </List>
  575. <ContextPrompts
  576. context={messages}
  577. updateContext={(updater) => {
  578. const newMessages = messages.slice();
  579. updater(newMessages);
  580. setMessages(newMessages);
  581. }}
  582. />
  583. </Modal>
  584. </div>
  585. );
  586. }
  587. export function DeleteImageButton(props: { deleteImage: () => void }) {
  588. return (
  589. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  590. <DeleteIcon />
  591. </div>
  592. );
  593. }
  594. function _Chat() {
  595. type RenderMessage = ChatMessage & { preview?: boolean };
  596. const chatStore = useChatStore();
  597. const session = chatStore.currentSession();
  598. const config = useAppConfig();
  599. const fontSize = config.fontSize;
  600. const [showExport, setShowExport] = useState(false);
  601. const inputRef = useRef<HTMLTextAreaElement>(null);
  602. const [userInput, setUserInput] = useState("");
  603. const [isLoading, setIsLoading] = useState(false);
  604. const { submitKey, shouldSubmit } = useSubmitHandler();
  605. const { scrollRef, setAutoScroll, scrollDomToBottom } = useScrollToBottom();
  606. const [hitBottom, setHitBottom] = useState(true);
  607. const isMobileScreen = useMobileScreen();
  608. const navigate = useNavigate();
  609. const [attachImages, setAttachImages] = useState<string[]>([]);
  610. const [uploading, setUploading] = useState(false);
  611. // prompt hints
  612. const promptStore = usePromptStore();
  613. const [promptHints, setPromptHints] = useState<RenderPompt[]>([]);
  614. const onSearch = useDebouncedCallback(
  615. (text: string) => {
  616. const matchedPrompts = promptStore.search(text);
  617. setPromptHints(matchedPrompts);
  618. },
  619. 100,
  620. { leading: true, trailing: true },
  621. );
  622. // auto grow input
  623. const [inputRows, setInputRows] = useState(2);
  624. const measure = useDebouncedCallback(
  625. () => {
  626. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  627. const inputRows = Math.min(
  628. 20,
  629. Math.max(2 + Number(!isMobileScreen), rows),
  630. );
  631. setInputRows(inputRows);
  632. },
  633. 100,
  634. {
  635. leading: true,
  636. trailing: true,
  637. },
  638. );
  639. // eslint-disable-next-line react-hooks/exhaustive-deps
  640. useEffect(measure, [userInput]);
  641. // chat commands shortcuts
  642. const chatCommands = useChatCommand({
  643. new: () => chatStore.newSession(),
  644. newm: () => navigate(Path.NewChat),
  645. prev: () => chatStore.nextSession(-1),
  646. next: () => chatStore.nextSession(1),
  647. clear: () =>
  648. chatStore.updateCurrentSession(
  649. (session) => (session.clearContextIndex = session.messages.length),
  650. ),
  651. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  652. });
  653. // only search prompts when user input is short
  654. const SEARCH_TEXT_LIMIT = 30;
  655. const onInput = (text: string) => {
  656. setUserInput(text);
  657. const n = text.trim().length;
  658. // clear search results
  659. if (n === 0) {
  660. setPromptHints([]);
  661. } else if (text.startsWith(ChatCommandPrefix)) {
  662. setPromptHints(chatCommands.search(text));
  663. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  664. // check if need to trigger auto completion
  665. if (text.startsWith("/")) {
  666. let searchText = text.slice(1);
  667. onSearch(searchText);
  668. }
  669. }
  670. };
  671. const doSubmit = (userInput: string) => {
  672. if (userInput.trim() === "") return;
  673. const matchCommand = chatCommands.match(userInput);
  674. if (matchCommand.matched) {
  675. setUserInput("");
  676. setPromptHints([]);
  677. matchCommand.invoke();
  678. return;
  679. }
  680. setIsLoading(true);
  681. chatStore
  682. .onUserInput(userInput, attachImages)
  683. .then(() => setIsLoading(false));
  684. setAttachImages([]);
  685. localStorage.setItem(LAST_INPUT_KEY, userInput);
  686. setUserInput("");
  687. setPromptHints([]);
  688. if (!isMobileScreen) inputRef.current?.focus();
  689. setAutoScroll(true);
  690. };
  691. const onPromptSelect = (prompt: RenderPompt) => {
  692. setTimeout(() => {
  693. setPromptHints([]);
  694. const matchedChatCommand = chatCommands.match(prompt.content);
  695. if (matchedChatCommand.matched) {
  696. // if user is selecting a chat command, just trigger it
  697. matchedChatCommand.invoke();
  698. setUserInput("");
  699. } else {
  700. // or fill the prompt
  701. setUserInput(prompt.content);
  702. }
  703. inputRef.current?.focus();
  704. }, 30);
  705. };
  706. // stop response
  707. const onUserStop = (messageId: string) => {
  708. ChatControllerPool.stop(session.id, messageId);
  709. };
  710. useEffect(() => {
  711. chatStore.updateCurrentSession((session) => {
  712. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  713. session.messages.forEach((m) => {
  714. // check if should stop all stale messages
  715. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  716. if (m.streaming) {
  717. m.streaming = false;
  718. }
  719. if (m.content.length === 0) {
  720. m.isError = true;
  721. m.content = prettyObject({
  722. error: true,
  723. message: "empty response",
  724. });
  725. }
  726. }
  727. });
  728. // auto sync mask config from global config
  729. if (session.mask.syncGlobalConfig) {
  730. console.log("[Mask] syncing from global, name = ", session.mask.name);
  731. session.mask.modelConfig = { ...config.modelConfig };
  732. }
  733. });
  734. // eslint-disable-next-line react-hooks/exhaustive-deps
  735. }, []);
  736. // check if should send message
  737. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  738. // if ArrowUp and no userInput, fill with last input
  739. if (
  740. e.key === "ArrowUp" &&
  741. userInput.length <= 0 &&
  742. !(e.metaKey || e.altKey || e.ctrlKey)
  743. ) {
  744. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  745. e.preventDefault();
  746. return;
  747. }
  748. if (shouldSubmit(e) && promptHints.length === 0) {
  749. doSubmit(userInput);
  750. e.preventDefault();
  751. }
  752. };
  753. const onRightClick = (e: any, message: ChatMessage) => {
  754. // copy to clipboard
  755. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  756. if (userInput.length === 0) {
  757. setUserInput(getMessageTextContent(message));
  758. }
  759. e.preventDefault();
  760. }
  761. };
  762. const deleteMessage = (msgId?: string) => {
  763. chatStore.updateCurrentSession(
  764. (session) =>
  765. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  766. );
  767. };
  768. const onDelete = (msgId: string) => {
  769. deleteMessage(msgId);
  770. };
  771. const onResend = (message: ChatMessage) => {
  772. // when it is resending a message
  773. // 1. for a user's message, find the next bot response
  774. // 2. for a bot's message, find the last user's input
  775. // 3. delete original user input and bot's message
  776. // 4. resend the user's input
  777. const resendingIndex = session.messages.findIndex(
  778. (m) => m.id === message.id,
  779. );
  780. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  781. console.error("[Chat] failed to find resending message", message);
  782. return;
  783. }
  784. let userMessage: ChatMessage | undefined;
  785. let botMessage: ChatMessage | undefined;
  786. if (message.role === "assistant") {
  787. // if it is resending a bot's message, find the user input for it
  788. botMessage = message;
  789. for (let i = resendingIndex; i >= 0; i -= 1) {
  790. if (session.messages[i].role === "user") {
  791. userMessage = session.messages[i];
  792. break;
  793. }
  794. }
  795. } else if (message.role === "user") {
  796. // if it is resending a user's input, find the bot's response
  797. userMessage = message;
  798. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  799. if (session.messages[i].role === "assistant") {
  800. botMessage = session.messages[i];
  801. break;
  802. }
  803. }
  804. }
  805. if (userMessage === undefined) {
  806. console.error("[Chat] failed to resend", message);
  807. return;
  808. }
  809. // delete the original messages
  810. deleteMessage(userMessage.id);
  811. deleteMessage(botMessage?.id);
  812. // resend the message
  813. setIsLoading(true);
  814. const textContent = getMessageTextContent(userMessage);
  815. const images = getMessageImages(userMessage);
  816. chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
  817. inputRef.current?.focus();
  818. };
  819. const onPinMessage = (message: ChatMessage) => {
  820. chatStore.updateCurrentSession((session) =>
  821. session.mask.context.push(message),
  822. );
  823. showToast(Locale.Chat.Actions.PinToastContent, {
  824. text: Locale.Chat.Actions.PinToastAction,
  825. onClick: () => {
  826. setShowPromptModal(true);
  827. },
  828. });
  829. };
  830. const context: RenderMessage[] = useMemo(() => {
  831. return session.mask.hideContext ? [] : session.mask.context.slice();
  832. }, [session.mask.context, session.mask.hideContext]);
  833. const accessStore = useAccessStore();
  834. if (
  835. context.length === 0 &&
  836. session.messages.at(0)?.content !== BOT_HELLO.content
  837. ) {
  838. const copiedHello = Object.assign({}, BOT_HELLO);
  839. if (!accessStore.isAuthorized()) {
  840. copiedHello.content = Locale.Error.Unauthorized;
  841. }
  842. context.push(copiedHello);
  843. }
  844. // preview messages
  845. const renderMessages = useMemo(() => {
  846. return context
  847. .concat(session.messages as RenderMessage[])
  848. .concat(
  849. isLoading
  850. ? [
  851. {
  852. ...createMessage({
  853. role: "assistant",
  854. content: "……",
  855. }),
  856. preview: true,
  857. },
  858. ]
  859. : [],
  860. )
  861. .concat(
  862. userInput.length > 0 && config.sendPreviewBubble
  863. ? [
  864. {
  865. ...createMessage({
  866. role: "user",
  867. content: userInput,
  868. }),
  869. preview: true,
  870. },
  871. ]
  872. : [],
  873. );
  874. }, [
  875. config.sendPreviewBubble,
  876. context,
  877. isLoading,
  878. session.messages,
  879. userInput,
  880. ]);
  881. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  882. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  883. );
  884. function setMsgRenderIndex(newIndex: number) {
  885. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  886. newIndex = Math.max(0, newIndex);
  887. _setMsgRenderIndex(newIndex);
  888. }
  889. const messages = useMemo(() => {
  890. const endRenderIndex = Math.min(
  891. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  892. renderMessages.length,
  893. );
  894. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  895. }, [msgRenderIndex, renderMessages]);
  896. const onChatBodyScroll = (e: HTMLElement) => {
  897. const bottomHeight = e.scrollTop + e.clientHeight;
  898. const edgeThreshold = e.clientHeight;
  899. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  900. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  901. const isHitBottom =
  902. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  903. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  904. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  905. if (isTouchTopEdge && !isTouchBottomEdge) {
  906. setMsgRenderIndex(prevPageMsgIndex);
  907. } else if (isTouchBottomEdge) {
  908. setMsgRenderIndex(nextPageMsgIndex);
  909. }
  910. setHitBottom(isHitBottom);
  911. setAutoScroll(isHitBottom);
  912. };
  913. function scrollToBottom() {
  914. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  915. scrollDomToBottom();
  916. }
  917. // clear context index = context length + index in messages
  918. const clearContextIndex =
  919. (session.clearContextIndex ?? -1) >= 0
  920. ? session.clearContextIndex! + context.length - msgRenderIndex
  921. : -1;
  922. const [showPromptModal, setShowPromptModal] = useState(false);
  923. const clientConfig = useMemo(() => getClientConfig(), []);
  924. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  925. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  926. useCommand({
  927. fill: setUserInput,
  928. submit: (text) => {
  929. doSubmit(text);
  930. },
  931. code: (text) => {
  932. if (accessStore.disableFastLink) return;
  933. console.log("[Command] got code from url: ", text);
  934. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  935. if (res) {
  936. accessStore.update((access) => (access.accessCode = text));
  937. }
  938. });
  939. },
  940. settings: (text) => {
  941. if (accessStore.disableFastLink) return;
  942. try {
  943. const payload = JSON.parse(text) as {
  944. key?: string;
  945. url?: string;
  946. };
  947. console.log("[Command] got settings from url: ", payload);
  948. if (payload.key || payload.url) {
  949. showConfirm(
  950. Locale.URLCommand.Settings +
  951. `\n${JSON.stringify(payload, null, 4)}`,
  952. ).then((res) => {
  953. if (!res) return;
  954. if (payload.key) {
  955. accessStore.update(
  956. (access) => (access.openaiApiKey = payload.key!),
  957. );
  958. }
  959. if (payload.url) {
  960. accessStore.update((access) => (access.openaiUrl = payload.url!));
  961. }
  962. });
  963. }
  964. } catch {
  965. console.error("[Command] failed to get settings from url: ", text);
  966. }
  967. },
  968. });
  969. // edit / insert message modal
  970. const [isEditingMessage, setIsEditingMessage] = useState(false);
  971. // remember unfinished input
  972. useEffect(() => {
  973. // try to load from local storage
  974. const key = UNFINISHED_INPUT(session.id);
  975. const mayBeUnfinishedInput = localStorage.getItem(key);
  976. if (mayBeUnfinishedInput && userInput.length === 0) {
  977. setUserInput(mayBeUnfinishedInput);
  978. localStorage.removeItem(key);
  979. }
  980. const dom = inputRef.current;
  981. return () => {
  982. localStorage.setItem(key, dom?.value ?? "");
  983. };
  984. // eslint-disable-next-line react-hooks/exhaustive-deps
  985. }, []);
  986. async function uploadImage() {
  987. const images: string[] = [];
  988. images.push(...attachImages);
  989. images.push(
  990. ...(await new Promise<string[]>((res, rej) => {
  991. const fileInput = document.createElement("input");
  992. fileInput.type = "file";
  993. fileInput.accept =
  994. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  995. fileInput.multiple = true;
  996. fileInput.onchange = (event: any) => {
  997. setUploading(true);
  998. const files = event.target.files;
  999. const imagesData: string[] = [];
  1000. for (let i = 0; i < files.length; i++) {
  1001. const file = event.target.files[i];
  1002. compressImage(file, 256 * 1024)
  1003. .then((dataUrl) => {
  1004. imagesData.push(dataUrl);
  1005. if (
  1006. imagesData.length === 3 ||
  1007. imagesData.length === files.length
  1008. ) {
  1009. setUploading(false);
  1010. res(imagesData);
  1011. }
  1012. })
  1013. .catch((e) => {
  1014. setUploading(false);
  1015. rej(e);
  1016. });
  1017. }
  1018. };
  1019. fileInput.click();
  1020. })),
  1021. );
  1022. const imagesLength = images.length;
  1023. if (imagesLength > 3) {
  1024. images.splice(3, imagesLength - 3);
  1025. }
  1026. setAttachImages(images);
  1027. }
  1028. return (
  1029. <div className={styles.chat} key={session.id}>
  1030. <div className="window-header" data-tauri-drag-region>
  1031. {isMobileScreen && (
  1032. <div className="window-actions">
  1033. <div className={"window-action-button"}>
  1034. <IconButton
  1035. icon={<ReturnIcon />}
  1036. bordered
  1037. title={Locale.Chat.Actions.ChatList}
  1038. onClick={() => navigate(Path.Home)}
  1039. />
  1040. </div>
  1041. </div>
  1042. )}
  1043. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  1044. <div
  1045. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  1046. onClickCapture={() => setIsEditingMessage(true)}
  1047. >
  1048. {!session.topic ? DEFAULT_TOPIC : session.topic}
  1049. </div>
  1050. <div className="window-header-sub-title">
  1051. {Locale.Chat.SubTitle(session.messages.length)}
  1052. </div>
  1053. </div>
  1054. <div className="window-actions">
  1055. {!isMobileScreen && (
  1056. <div className="window-action-button">
  1057. <IconButton
  1058. icon={<RenameIcon />}
  1059. bordered
  1060. onClick={() => setIsEditingMessage(true)}
  1061. />
  1062. </div>
  1063. )}
  1064. <div className="window-action-button">
  1065. <IconButton
  1066. icon={<ExportIcon />}
  1067. bordered
  1068. title={Locale.Chat.Actions.Export}
  1069. onClick={() => {
  1070. setShowExport(true);
  1071. }}
  1072. />
  1073. </div>
  1074. {showMaxIcon && (
  1075. <div className="window-action-button">
  1076. <IconButton
  1077. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1078. bordered
  1079. onClick={() => {
  1080. config.update(
  1081. (config) => (config.tightBorder = !config.tightBorder),
  1082. );
  1083. }}
  1084. />
  1085. </div>
  1086. )}
  1087. </div>
  1088. <PromptToast
  1089. showToast={!hitBottom}
  1090. showModal={showPromptModal}
  1091. setShowModal={setShowPromptModal}
  1092. />
  1093. </div>
  1094. <div
  1095. className={styles["chat-body"]}
  1096. ref={scrollRef}
  1097. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1098. onMouseDown={() => inputRef.current?.blur()}
  1099. onTouchStart={() => {
  1100. inputRef.current?.blur();
  1101. setAutoScroll(false);
  1102. }}
  1103. >
  1104. {messages.map((message, i) => {
  1105. const isUser = message.role === "user";
  1106. const isContext = i < context.length;
  1107. const showActions =
  1108. i > 0 &&
  1109. !(message.preview || message.content.length === 0) &&
  1110. !isContext;
  1111. const showTyping = message.preview || message.streaming;
  1112. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1113. return (
  1114. <Fragment key={message.id}>
  1115. <div
  1116. className={
  1117. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1118. }
  1119. >
  1120. <div className={styles["chat-message-container"]}>
  1121. <div className={styles["chat-message-header"]}>
  1122. <div className={styles["chat-message-avatar"]}>
  1123. <div className={styles["chat-message-edit"]}>
  1124. <IconButton
  1125. icon={<EditIcon />}
  1126. onClick={async () => {
  1127. const newMessage = await showPrompt(
  1128. Locale.Chat.Actions.Edit,
  1129. getMessageTextContent(message),
  1130. 10,
  1131. );
  1132. let newContent: string | MultimodalContent[] =
  1133. newMessage;
  1134. const images = getMessageImages(message);
  1135. if (images.length > 0) {
  1136. newContent = [{ type: "text", text: newMessage }];
  1137. for (let i = 0; i < images.length; i++) {
  1138. newContent.push({
  1139. type: "image_url",
  1140. image_url: {
  1141. url: images[i],
  1142. },
  1143. });
  1144. }
  1145. }
  1146. chatStore.updateCurrentSession((session) => {
  1147. const m = session.mask.context
  1148. .concat(session.messages)
  1149. .find((m) => m.id === message.id);
  1150. if (m) {
  1151. m.content = newContent;
  1152. }
  1153. });
  1154. }}
  1155. ></IconButton>
  1156. </div>
  1157. {isUser ? (
  1158. <Avatar avatar={config.avatar} />
  1159. ) : (
  1160. <>
  1161. {["system"].includes(message.role) ? (
  1162. <Avatar avatar="2699-fe0f" />
  1163. ) : (
  1164. <MaskAvatar
  1165. avatar={session.mask.avatar}
  1166. model={
  1167. message.model || session.mask.modelConfig.model
  1168. }
  1169. />
  1170. )}
  1171. </>
  1172. )}
  1173. </div>
  1174. {showActions && (
  1175. <div className={styles["chat-message-actions"]}>
  1176. <div className={styles["chat-input-actions"]}>
  1177. {message.streaming ? (
  1178. <ChatAction
  1179. text={Locale.Chat.Actions.Stop}
  1180. icon={<StopIcon />}
  1181. onClick={() => onUserStop(message.id ?? i)}
  1182. />
  1183. ) : (
  1184. <>
  1185. <ChatAction
  1186. text={Locale.Chat.Actions.Retry}
  1187. icon={<ResetIcon />}
  1188. onClick={() => onResend(message)}
  1189. />
  1190. <ChatAction
  1191. text={Locale.Chat.Actions.Delete}
  1192. icon={<DeleteIcon />}
  1193. onClick={() => onDelete(message.id ?? i)}
  1194. />
  1195. <ChatAction
  1196. text={Locale.Chat.Actions.Pin}
  1197. icon={<PinIcon />}
  1198. onClick={() => onPinMessage(message)}
  1199. />
  1200. <ChatAction
  1201. text={Locale.Chat.Actions.Copy}
  1202. icon={<CopyIcon />}
  1203. onClick={() =>
  1204. copyToClipboard(
  1205. getMessageTextContent(message),
  1206. )
  1207. }
  1208. />
  1209. </>
  1210. )}
  1211. </div>
  1212. </div>
  1213. )}
  1214. </div>
  1215. {showTyping && (
  1216. <div className={styles["chat-message-status"]}>
  1217. {Locale.Chat.Typing}
  1218. </div>
  1219. )}
  1220. <div className={styles["chat-message-item"]}>
  1221. <Markdown
  1222. content={getMessageTextContent(message)}
  1223. loading={
  1224. (message.preview || message.streaming) &&
  1225. message.content.length === 0 &&
  1226. !isUser
  1227. }
  1228. onContextMenu={(e) => onRightClick(e, message)}
  1229. onDoubleClickCapture={() => {
  1230. if (!isMobileScreen) return;
  1231. setUserInput(getMessageTextContent(message));
  1232. }}
  1233. fontSize={fontSize}
  1234. parentRef={scrollRef}
  1235. defaultShow={i >= messages.length - 6}
  1236. />
  1237. {getMessageImages(message).length == 1 && (
  1238. <img
  1239. className={styles["chat-message-item-image"]}
  1240. src={getMessageImages(message)[0]}
  1241. alt=""
  1242. />
  1243. )}
  1244. {getMessageImages(message).length > 1 && (
  1245. <div
  1246. className={styles["chat-message-item-images"]}
  1247. style={
  1248. {
  1249. "--image-count": getMessageImages(message).length,
  1250. } as React.CSSProperties
  1251. }
  1252. >
  1253. {getMessageImages(message).map((image, index) => {
  1254. return (
  1255. <img
  1256. className={
  1257. styles["chat-message-item-image-multi"]
  1258. }
  1259. key={index}
  1260. src={image}
  1261. alt=""
  1262. />
  1263. );
  1264. })}
  1265. </div>
  1266. )}
  1267. </div>
  1268. <div className={styles["chat-message-action-date"]}>
  1269. {isContext
  1270. ? Locale.Chat.IsContext
  1271. : message.date.toLocaleString()}
  1272. </div>
  1273. </div>
  1274. </div>
  1275. {shouldShowClearContextDivider && <ClearContextDivider />}
  1276. </Fragment>
  1277. );
  1278. })}
  1279. </div>
  1280. <div className={styles["chat-input-panel"]}>
  1281. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  1282. <ChatActions
  1283. uploadImage={uploadImage}
  1284. setAttachImages={setAttachImages}
  1285. setUploading={setUploading}
  1286. showPromptModal={() => setShowPromptModal(true)}
  1287. scrollToBottom={scrollToBottom}
  1288. hitBottom={hitBottom}
  1289. uploading={uploading}
  1290. showPromptHints={() => {
  1291. // Click again to close
  1292. if (promptHints.length > 0) {
  1293. setPromptHints([]);
  1294. return;
  1295. }
  1296. inputRef.current?.focus();
  1297. setUserInput("/");
  1298. onSearch("");
  1299. }}
  1300. />
  1301. <label
  1302. className={`${styles["chat-input-panel-inner"]} ${
  1303. attachImages.length != 0
  1304. ? styles["chat-input-panel-inner-attach"]
  1305. : ""
  1306. }`}
  1307. htmlFor="chat-input"
  1308. >
  1309. <textarea
  1310. id="chat-input"
  1311. ref={inputRef}
  1312. className={styles["chat-input"]}
  1313. placeholder={Locale.Chat.Input(submitKey)}
  1314. onInput={(e) => onInput(e.currentTarget.value)}
  1315. value={userInput}
  1316. onKeyDown={onInputKeyDown}
  1317. onFocus={scrollToBottom}
  1318. onClick={scrollToBottom}
  1319. rows={inputRows}
  1320. autoFocus={autoFocus}
  1321. style={{
  1322. fontSize: config.fontSize,
  1323. }}
  1324. />
  1325. {attachImages.length != 0 && (
  1326. <div className={styles["attach-images"]}>
  1327. {attachImages.map((image, index) => {
  1328. return (
  1329. <div
  1330. key={index}
  1331. className={styles["attach-image"]}
  1332. style={{ backgroundImage: `url("${image}")` }}
  1333. >
  1334. <div className={styles["attach-image-mask"]}>
  1335. <DeleteImageButton
  1336. deleteImage={() => {
  1337. setAttachImages(
  1338. attachImages.filter((_, i) => i !== index),
  1339. );
  1340. }}
  1341. />
  1342. </div>
  1343. </div>
  1344. );
  1345. })}
  1346. </div>
  1347. )}
  1348. <IconButton
  1349. icon={<SendWhiteIcon />}
  1350. text={Locale.Chat.Send}
  1351. className={styles["chat-input-send"]}
  1352. type="primary"
  1353. onClick={() => doSubmit(userInput)}
  1354. />
  1355. </label>
  1356. </div>
  1357. {showExport && (
  1358. <ExportMessageModal onClose={() => setShowExport(false)} />
  1359. )}
  1360. {isEditingMessage && (
  1361. <EditMessageModal
  1362. onClose={() => {
  1363. setIsEditingMessage(false);
  1364. }}
  1365. />
  1366. )}
  1367. </div>
  1368. );
  1369. }
  1370. export function Chat() {
  1371. const chatStore = useChatStore();
  1372. const sessionIndex = chatStore.currentSessionIndex;
  1373. return <_Chat key={sessionIndex}></_Chat>;
  1374. }