chat.tsx 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550
  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 items = (event.clipboardData || window.clipboardData).items;
  1002. for (const item of items) {
  1003. if (item.kind === "file" && item.type.startsWith("image/")) {
  1004. event.preventDefault();
  1005. const file = item.getAsFile();
  1006. if (file) {
  1007. const images: string[] = [];
  1008. images.push(...attachImages);
  1009. images.push(
  1010. ...(await new Promise<string[]>((res, rej) => {
  1011. setUploading(true);
  1012. const imagesData: string[] = [];
  1013. compressImage(file, 256 * 1024)
  1014. .then((dataUrl) => {
  1015. imagesData.push(dataUrl);
  1016. setUploading(false);
  1017. res(imagesData);
  1018. })
  1019. .catch((e) => {
  1020. setUploading(false);
  1021. rej(e);
  1022. });
  1023. })),
  1024. );
  1025. const imagesLength = images.length;
  1026. if (imagesLength > 3) {
  1027. images.splice(3, imagesLength - 3);
  1028. }
  1029. setAttachImages(images);
  1030. }
  1031. }
  1032. }
  1033. },
  1034. [attachImages],
  1035. );
  1036. async function uploadImage() {
  1037. const images: string[] = [];
  1038. images.push(...attachImages);
  1039. images.push(
  1040. ...(await new Promise<string[]>((res, rej) => {
  1041. const fileInput = document.createElement("input");
  1042. fileInput.type = "file";
  1043. fileInput.accept =
  1044. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1045. fileInput.multiple = true;
  1046. fileInput.onchange = (event: any) => {
  1047. setUploading(true);
  1048. const files = event.target.files;
  1049. const imagesData: string[] = [];
  1050. for (let i = 0; i < files.length; i++) {
  1051. const file = event.target.files[i];
  1052. compressImage(file, 256 * 1024)
  1053. .then((dataUrl) => {
  1054. imagesData.push(dataUrl);
  1055. if (
  1056. imagesData.length === 3 ||
  1057. imagesData.length === files.length
  1058. ) {
  1059. setUploading(false);
  1060. res(imagesData);
  1061. }
  1062. })
  1063. .catch((e) => {
  1064. setUploading(false);
  1065. rej(e);
  1066. });
  1067. }
  1068. };
  1069. fileInput.click();
  1070. })),
  1071. );
  1072. const imagesLength = images.length;
  1073. if (imagesLength > 3) {
  1074. images.splice(3, imagesLength - 3);
  1075. }
  1076. setAttachImages(images);
  1077. }
  1078. return (
  1079. <div className={styles.chat} key={session.id}>
  1080. <div className="window-header" data-tauri-drag-region>
  1081. {isMobileScreen && (
  1082. <div className="window-actions">
  1083. <div className={"window-action-button"}>
  1084. <IconButton
  1085. icon={<ReturnIcon />}
  1086. bordered
  1087. title={Locale.Chat.Actions.ChatList}
  1088. onClick={() => navigate(Path.Home)}
  1089. />
  1090. </div>
  1091. </div>
  1092. )}
  1093. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  1094. <div
  1095. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  1096. onClickCapture={() => setIsEditingMessage(true)}
  1097. >
  1098. {!session.topic ? DEFAULT_TOPIC : session.topic}
  1099. </div>
  1100. <div className="window-header-sub-title">
  1101. {Locale.Chat.SubTitle(session.messages.length)}
  1102. </div>
  1103. </div>
  1104. <div className="window-actions">
  1105. {!isMobileScreen && (
  1106. <div className="window-action-button">
  1107. <IconButton
  1108. icon={<RenameIcon />}
  1109. bordered
  1110. onClick={() => setIsEditingMessage(true)}
  1111. />
  1112. </div>
  1113. )}
  1114. <div className="window-action-button">
  1115. <IconButton
  1116. icon={<ExportIcon />}
  1117. bordered
  1118. title={Locale.Chat.Actions.Export}
  1119. onClick={() => {
  1120. setShowExport(true);
  1121. }}
  1122. />
  1123. </div>
  1124. {showMaxIcon && (
  1125. <div className="window-action-button">
  1126. <IconButton
  1127. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1128. bordered
  1129. onClick={() => {
  1130. config.update(
  1131. (config) => (config.tightBorder = !config.tightBorder),
  1132. );
  1133. }}
  1134. />
  1135. </div>
  1136. )}
  1137. </div>
  1138. <PromptToast
  1139. showToast={!hitBottom}
  1140. showModal={showPromptModal}
  1141. setShowModal={setShowPromptModal}
  1142. />
  1143. </div>
  1144. <div
  1145. className={styles["chat-body"]}
  1146. ref={scrollRef}
  1147. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1148. onMouseDown={() => inputRef.current?.blur()}
  1149. onTouchStart={() => {
  1150. inputRef.current?.blur();
  1151. setAutoScroll(false);
  1152. }}
  1153. >
  1154. {messages.map((message, i) => {
  1155. const isUser = message.role === "user";
  1156. const isContext = i < context.length;
  1157. const showActions =
  1158. i > 0 &&
  1159. !(message.preview || message.content.length === 0) &&
  1160. !isContext;
  1161. const showTyping = message.preview || message.streaming;
  1162. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1163. return (
  1164. <Fragment key={message.id}>
  1165. <div
  1166. className={
  1167. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1168. }
  1169. >
  1170. <div className={styles["chat-message-container"]}>
  1171. <div className={styles["chat-message-header"]}>
  1172. <div className={styles["chat-message-avatar"]}>
  1173. <div className={styles["chat-message-edit"]}>
  1174. <IconButton
  1175. icon={<EditIcon />}
  1176. onClick={async () => {
  1177. const newMessage = await showPrompt(
  1178. Locale.Chat.Actions.Edit,
  1179. getMessageTextContent(message),
  1180. 10,
  1181. );
  1182. let newContent: string | MultimodalContent[] =
  1183. newMessage;
  1184. const images = getMessageImages(message);
  1185. if (images.length > 0) {
  1186. newContent = [{ type: "text", text: newMessage }];
  1187. for (let i = 0; i < images.length; i++) {
  1188. newContent.push({
  1189. type: "image_url",
  1190. image_url: {
  1191. url: images[i],
  1192. },
  1193. });
  1194. }
  1195. }
  1196. chatStore.updateCurrentSession((session) => {
  1197. const m = session.mask.context
  1198. .concat(session.messages)
  1199. .find((m) => m.id === message.id);
  1200. if (m) {
  1201. m.content = newContent;
  1202. }
  1203. });
  1204. }}
  1205. ></IconButton>
  1206. </div>
  1207. {isUser ? (
  1208. <Avatar avatar={config.avatar} />
  1209. ) : (
  1210. <>
  1211. {["system"].includes(message.role) ? (
  1212. <Avatar avatar="2699-fe0f" />
  1213. ) : (
  1214. <MaskAvatar
  1215. avatar={session.mask.avatar}
  1216. model={
  1217. message.model || session.mask.modelConfig.model
  1218. }
  1219. />
  1220. )}
  1221. </>
  1222. )}
  1223. </div>
  1224. {showActions && (
  1225. <div className={styles["chat-message-actions"]}>
  1226. <div className={styles["chat-input-actions"]}>
  1227. {message.streaming ? (
  1228. <ChatAction
  1229. text={Locale.Chat.Actions.Stop}
  1230. icon={<StopIcon />}
  1231. onClick={() => onUserStop(message.id ?? i)}
  1232. />
  1233. ) : (
  1234. <>
  1235. <ChatAction
  1236. text={Locale.Chat.Actions.Retry}
  1237. icon={<ResetIcon />}
  1238. onClick={() => onResend(message)}
  1239. />
  1240. <ChatAction
  1241. text={Locale.Chat.Actions.Delete}
  1242. icon={<DeleteIcon />}
  1243. onClick={() => onDelete(message.id ?? i)}
  1244. />
  1245. <ChatAction
  1246. text={Locale.Chat.Actions.Pin}
  1247. icon={<PinIcon />}
  1248. onClick={() => onPinMessage(message)}
  1249. />
  1250. <ChatAction
  1251. text={Locale.Chat.Actions.Copy}
  1252. icon={<CopyIcon />}
  1253. onClick={() =>
  1254. copyToClipboard(
  1255. getMessageTextContent(message),
  1256. )
  1257. }
  1258. />
  1259. </>
  1260. )}
  1261. </div>
  1262. </div>
  1263. )}
  1264. </div>
  1265. {showTyping && (
  1266. <div className={styles["chat-message-status"]}>
  1267. {Locale.Chat.Typing}
  1268. </div>
  1269. )}
  1270. <div className={styles["chat-message-item"]}>
  1271. <Markdown
  1272. content={getMessageTextContent(message)}
  1273. loading={
  1274. (message.preview || message.streaming) &&
  1275. message.content.length === 0 &&
  1276. !isUser
  1277. }
  1278. onContextMenu={(e) => onRightClick(e, message)}
  1279. onDoubleClickCapture={() => {
  1280. if (!isMobileScreen) return;
  1281. setUserInput(getMessageTextContent(message));
  1282. }}
  1283. fontSize={fontSize}
  1284. parentRef={scrollRef}
  1285. defaultShow={i >= messages.length - 6}
  1286. />
  1287. {getMessageImages(message).length == 1 && (
  1288. <img
  1289. className={styles["chat-message-item-image"]}
  1290. src={getMessageImages(message)[0]}
  1291. alt=""
  1292. />
  1293. )}
  1294. {getMessageImages(message).length > 1 && (
  1295. <div
  1296. className={styles["chat-message-item-images"]}
  1297. style={
  1298. {
  1299. "--image-count": getMessageImages(message).length,
  1300. } as React.CSSProperties
  1301. }
  1302. >
  1303. {getMessageImages(message).map((image, index) => {
  1304. return (
  1305. <img
  1306. className={
  1307. styles["chat-message-item-image-multi"]
  1308. }
  1309. key={index}
  1310. src={image}
  1311. alt=""
  1312. />
  1313. );
  1314. })}
  1315. </div>
  1316. )}
  1317. </div>
  1318. <div className={styles["chat-message-action-date"]}>
  1319. {isContext
  1320. ? Locale.Chat.IsContext
  1321. : message.date.toLocaleString()}
  1322. </div>
  1323. </div>
  1324. </div>
  1325. {shouldShowClearContextDivider && <ClearContextDivider />}
  1326. </Fragment>
  1327. );
  1328. })}
  1329. </div>
  1330. <div className={styles["chat-input-panel"]}>
  1331. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  1332. <ChatActions
  1333. uploadImage={uploadImage}
  1334. setAttachImages={setAttachImages}
  1335. setUploading={setUploading}
  1336. showPromptModal={() => setShowPromptModal(true)}
  1337. scrollToBottom={scrollToBottom}
  1338. hitBottom={hitBottom}
  1339. uploading={uploading}
  1340. showPromptHints={() => {
  1341. // Click again to close
  1342. if (promptHints.length > 0) {
  1343. setPromptHints([]);
  1344. return;
  1345. }
  1346. inputRef.current?.focus();
  1347. setUserInput("/");
  1348. onSearch("");
  1349. }}
  1350. />
  1351. <label
  1352. className={`${styles["chat-input-panel-inner"]} ${
  1353. attachImages.length != 0
  1354. ? styles["chat-input-panel-inner-attach"]
  1355. : ""
  1356. }`}
  1357. htmlFor="chat-input"
  1358. >
  1359. <textarea
  1360. id="chat-input"
  1361. ref={inputRef}
  1362. className={styles["chat-input"]}
  1363. placeholder={Locale.Chat.Input(submitKey)}
  1364. onInput={(e) => onInput(e.currentTarget.value)}
  1365. value={userInput}
  1366. onKeyDown={onInputKeyDown}
  1367. onFocus={scrollToBottom}
  1368. onClick={scrollToBottom}
  1369. onPaste={handlePaste}
  1370. rows={inputRows}
  1371. autoFocus={autoFocus}
  1372. style={{
  1373. fontSize: config.fontSize,
  1374. }}
  1375. />
  1376. {attachImages.length != 0 && (
  1377. <div className={styles["attach-images"]}>
  1378. {attachImages.map((image, index) => {
  1379. return (
  1380. <div
  1381. key={index}
  1382. className={styles["attach-image"]}
  1383. style={{ backgroundImage: `url("${image}")` }}
  1384. >
  1385. <div className={styles["attach-image-mask"]}>
  1386. <DeleteImageButton
  1387. deleteImage={() => {
  1388. setAttachImages(
  1389. attachImages.filter((_, i) => i !== index),
  1390. );
  1391. }}
  1392. />
  1393. </div>
  1394. </div>
  1395. );
  1396. })}
  1397. </div>
  1398. )}
  1399. <IconButton
  1400. icon={<SendWhiteIcon />}
  1401. text={Locale.Chat.Send}
  1402. className={styles["chat-input-send"]}
  1403. type="primary"
  1404. onClick={() => doSubmit(userInput)}
  1405. />
  1406. </label>
  1407. </div>
  1408. {showExport && (
  1409. <ExportMessageModal onClose={() => setShowExport(false)} />
  1410. )}
  1411. {isEditingMessage && (
  1412. <EditMessageModal
  1413. onClose={() => {
  1414. setIsEditingMessage(false);
  1415. }}
  1416. />
  1417. )}
  1418. </div>
  1419. );
  1420. }
  1421. export function Chat() {
  1422. const chatStore = useChatStore();
  1423. const sessionIndex = chatStore.currentSessionIndex;
  1424. return <_Chat key={sessionIndex}></_Chat>;
  1425. }