chat.tsx 47 KB

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