chat.tsx 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556
  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. } else {
  422. // 为visionModel时不附带历史消息
  423. const newModelConfig = chatStore.currentSession().mask.modelConfig;
  424. newModelConfig.historyMessageCount = 0;
  425. }
  426. // if current model is not available
  427. // switch to first available model
  428. const isUnavaliableModel = !models.some((m) => m.name === currentModel);
  429. if (isUnavaliableModel && models.length > 0) {
  430. const nextModel = models[0].name as ModelType;
  431. chatStore.updateCurrentSession(
  432. (session) => (session.mask.modelConfig.model = nextModel),
  433. );
  434. showToast(nextModel);
  435. }
  436. }, [chatStore, currentModel, models]);
  437. return (
  438. <div className={styles["chat-input-actions"]}>
  439. {couldStop && (
  440. <ChatAction
  441. onClick={stopAll}
  442. text={Locale.Chat.InputActions.Stop}
  443. icon={<StopIcon />}
  444. />
  445. )}
  446. {!props.hitBottom && (
  447. <ChatAction
  448. onClick={props.scrollToBottom}
  449. text={Locale.Chat.InputActions.ToBottom}
  450. icon={<BottomIcon />}
  451. />
  452. )}
  453. {props.hitBottom && (
  454. <ChatAction
  455. onClick={props.showPromptModal}
  456. text={Locale.Chat.InputActions.Settings}
  457. icon={<SettingsIcon />}
  458. />
  459. )}
  460. {showUploadImage && (
  461. <ChatAction
  462. onClick={props.uploadImage}
  463. text={Locale.Chat.InputActions.UploadImage}
  464. icon={props.uploading ? <LoadingButtonIcon /> : <ImageIcon />}
  465. />
  466. )}
  467. <ChatAction
  468. onClick={nextTheme}
  469. text={Locale.Chat.InputActions.Theme[theme]}
  470. icon={
  471. <>
  472. {theme === Theme.Auto ? (
  473. <AutoIcon />
  474. ) : theme === Theme.Light ? (
  475. <LightIcon />
  476. ) : theme === Theme.Dark ? (
  477. <DarkIcon />
  478. ) : null}
  479. </>
  480. }
  481. />
  482. <ChatAction
  483. onClick={props.showPromptHints}
  484. text={Locale.Chat.InputActions.Prompt}
  485. icon={<PromptIcon />}
  486. />
  487. <ChatAction
  488. onClick={() => {
  489. navigate(Path.Masks);
  490. }}
  491. text={Locale.Chat.InputActions.Masks}
  492. icon={<MaskIcon />}
  493. />
  494. <ChatAction
  495. text={Locale.Chat.InputActions.Clear}
  496. icon={<BreakIcon />}
  497. onClick={() => {
  498. chatStore.updateCurrentSession((session) => {
  499. if (session.clearContextIndex === session.messages.length) {
  500. session.clearContextIndex = undefined;
  501. } else {
  502. session.clearContextIndex = session.messages.length;
  503. session.memoryPrompt = ""; // will clear memory
  504. }
  505. });
  506. }}
  507. />
  508. <ChatAction
  509. onClick={() => setShowModelSelector(true)}
  510. text={currentModel}
  511. icon={<RobotIcon />}
  512. />
  513. {showModelSelector && (
  514. <Selector
  515. defaultSelectedValue={currentModel}
  516. items={models.map((m) => ({
  517. title: m.displayName,
  518. value: m.name,
  519. }))}
  520. onClose={() => setShowModelSelector(false)}
  521. onSelection={(s) => {
  522. if (s.length === 0) return;
  523. chatStore.updateCurrentSession((session) => {
  524. session.mask.modelConfig.model = s[0] as ModelType;
  525. session.mask.syncGlobalConfig = false;
  526. });
  527. showToast(s[0]);
  528. }}
  529. />
  530. )}
  531. </div>
  532. );
  533. }
  534. export function EditMessageModal(props: { onClose: () => void }) {
  535. const chatStore = useChatStore();
  536. const session = chatStore.currentSession();
  537. const [messages, setMessages] = useState(session.messages.slice());
  538. return (
  539. <div className="modal-mask">
  540. <Modal
  541. title={Locale.Chat.EditMessage.Title}
  542. onClose={props.onClose}
  543. actions={[
  544. <IconButton
  545. text={Locale.UI.Cancel}
  546. icon={<CancelIcon />}
  547. key="cancel"
  548. onClick={() => {
  549. props.onClose();
  550. }}
  551. />,
  552. <IconButton
  553. type="primary"
  554. text={Locale.UI.Confirm}
  555. icon={<ConfirmIcon />}
  556. key="ok"
  557. onClick={() => {
  558. chatStore.updateCurrentSession(
  559. (session) => (session.messages = messages),
  560. );
  561. props.onClose();
  562. }}
  563. />,
  564. ]}
  565. >
  566. <List>
  567. <ListItem
  568. title={Locale.Chat.EditMessage.Topic.Title}
  569. subTitle={Locale.Chat.EditMessage.Topic.SubTitle}
  570. >
  571. <input
  572. type="text"
  573. value={session.topic}
  574. onInput={(e) =>
  575. chatStore.updateCurrentSession(
  576. (session) => (session.topic = e.currentTarget.value),
  577. )
  578. }
  579. ></input>
  580. </ListItem>
  581. </List>
  582. <ContextPrompts
  583. context={messages}
  584. updateContext={(updater) => {
  585. const newMessages = messages.slice();
  586. updater(newMessages);
  587. setMessages(newMessages);
  588. }}
  589. />
  590. </Modal>
  591. </div>
  592. );
  593. }
  594. export function DeleteImageButton(props: { deleteImage: () => void }) {
  595. return (
  596. <div className={styles["delete-image"]} onClick={props.deleteImage}>
  597. <DeleteIcon />
  598. </div>
  599. );
  600. }
  601. function _Chat() {
  602. type RenderMessage = ChatMessage & { preview?: boolean };
  603. const chatStore = useChatStore();
  604. const session = chatStore.currentSession();
  605. const config = useAppConfig();
  606. const fontSize = config.fontSize;
  607. const [showExport, setShowExport] = useState(false);
  608. const inputRef = useRef<HTMLTextAreaElement>(null);
  609. const [userInput, setUserInput] = useState("");
  610. const [isLoading, setIsLoading] = useState(false);
  611. const { submitKey, shouldSubmit } = useSubmitHandler();
  612. const scrollRef = useRef<HTMLDivElement>(null);
  613. const isScrolledToBottom = scrollRef?.current
  614. ? Math.abs(
  615. scrollRef.current.scrollHeight -
  616. (scrollRef.current.scrollTop + scrollRef.current.clientHeight),
  617. ) <= 1
  618. : false;
  619. const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
  620. scrollRef,
  621. isScrolledToBottom,
  622. );
  623. const [hitBottom, setHitBottom] = useState(true);
  624. const isMobileScreen = useMobileScreen();
  625. const navigate = useNavigate();
  626. const [attachImages, setAttachImages] = useState<string[]>([]);
  627. const [uploading, setUploading] = useState(false);
  628. // prompt hints
  629. const promptStore = usePromptStore();
  630. const [promptHints, setPromptHints] = useState<RenderPompt[]>([]);
  631. const onSearch = useDebouncedCallback(
  632. (text: string) => {
  633. const matchedPrompts = promptStore.search(text);
  634. setPromptHints(matchedPrompts);
  635. },
  636. 100,
  637. { leading: true, trailing: true },
  638. );
  639. // auto grow input
  640. const [inputRows, setInputRows] = useState(2);
  641. const measure = useDebouncedCallback(
  642. () => {
  643. const rows = inputRef.current ? autoGrowTextArea(inputRef.current) : 1;
  644. const inputRows = Math.min(
  645. 20,
  646. Math.max(2 + Number(!isMobileScreen), rows),
  647. );
  648. setInputRows(inputRows);
  649. },
  650. 100,
  651. {
  652. leading: true,
  653. trailing: true,
  654. },
  655. );
  656. // eslint-disable-next-line react-hooks/exhaustive-deps
  657. useEffect(measure, [userInput]);
  658. // chat commands shortcuts
  659. const chatCommands = useChatCommand({
  660. new: () => chatStore.newSession(),
  661. newm: () => navigate(Path.NewChat),
  662. prev: () => chatStore.nextSession(-1),
  663. next: () => chatStore.nextSession(1),
  664. clear: () =>
  665. chatStore.updateCurrentSession(
  666. (session) => (session.clearContextIndex = session.messages.length),
  667. ),
  668. del: () => chatStore.deleteSession(chatStore.currentSessionIndex),
  669. });
  670. // only search prompts when user input is short
  671. const SEARCH_TEXT_LIMIT = 30;
  672. const onInput = (text: string) => {
  673. setUserInput(text);
  674. const n = text.trim().length;
  675. // clear search results
  676. if (n === 0) {
  677. setPromptHints([]);
  678. } else if (text.startsWith(ChatCommandPrefix)) {
  679. setPromptHints(chatCommands.search(text));
  680. } else if (!config.disablePromptHint && n < SEARCH_TEXT_LIMIT) {
  681. // check if need to trigger auto completion
  682. if (text.startsWith("/")) {
  683. let searchText = text.slice(1);
  684. onSearch(searchText);
  685. }
  686. }
  687. };
  688. const doSubmit = (userInput: string) => {
  689. if (userInput.trim() === "") return;
  690. const matchCommand = chatCommands.match(userInput);
  691. if (matchCommand.matched) {
  692. setUserInput("");
  693. setPromptHints([]);
  694. matchCommand.invoke();
  695. return;
  696. }
  697. setIsLoading(true);
  698. chatStore
  699. .onUserInput(userInput, attachImages)
  700. .then(() => setIsLoading(false));
  701. setAttachImages([]);
  702. localStorage.setItem(LAST_INPUT_KEY, userInput);
  703. setUserInput("");
  704. setPromptHints([]);
  705. if (!isMobileScreen) inputRef.current?.focus();
  706. setAutoScroll(true);
  707. };
  708. const onPromptSelect = (prompt: RenderPompt) => {
  709. setTimeout(() => {
  710. setPromptHints([]);
  711. const matchedChatCommand = chatCommands.match(prompt.content);
  712. if (matchedChatCommand.matched) {
  713. // if user is selecting a chat command, just trigger it
  714. matchedChatCommand.invoke();
  715. setUserInput("");
  716. } else {
  717. // or fill the prompt
  718. setUserInput(prompt.content);
  719. }
  720. inputRef.current?.focus();
  721. }, 30);
  722. };
  723. // stop response
  724. const onUserStop = (messageId: string) => {
  725. ChatControllerPool.stop(session.id, messageId);
  726. };
  727. useEffect(() => {
  728. chatStore.updateCurrentSession((session) => {
  729. const stopTiming = Date.now() - REQUEST_TIMEOUT_MS;
  730. session.messages.forEach((m) => {
  731. // check if should stop all stale messages
  732. if (m.isError || new Date(m.date).getTime() < stopTiming) {
  733. if (m.streaming) {
  734. m.streaming = false;
  735. }
  736. if (m.content.length === 0) {
  737. m.isError = true;
  738. m.content = prettyObject({
  739. error: true,
  740. message: "empty response",
  741. });
  742. }
  743. }
  744. });
  745. // auto sync mask config from global config
  746. if (session.mask.syncGlobalConfig) {
  747. console.log("[Mask] syncing from global, name = ", session.mask.name);
  748. session.mask.modelConfig = { ...config.modelConfig };
  749. }
  750. });
  751. // eslint-disable-next-line react-hooks/exhaustive-deps
  752. }, []);
  753. // check if should send message
  754. const onInputKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  755. // if ArrowUp and no userInput, fill with last input
  756. if (
  757. e.key === "ArrowUp" &&
  758. userInput.length <= 0 &&
  759. !(e.metaKey || e.altKey || e.ctrlKey)
  760. ) {
  761. setUserInput(localStorage.getItem(LAST_INPUT_KEY) ?? "");
  762. e.preventDefault();
  763. return;
  764. }
  765. if (shouldSubmit(e) && promptHints.length === 0) {
  766. doSubmit(userInput);
  767. e.preventDefault();
  768. }
  769. };
  770. const onRightClick = (e: any, message: ChatMessage) => {
  771. // copy to clipboard
  772. if (selectOrCopy(e.currentTarget, getMessageTextContent(message))) {
  773. if (userInput.length === 0) {
  774. setUserInput(getMessageTextContent(message));
  775. }
  776. e.preventDefault();
  777. }
  778. };
  779. const deleteMessage = (msgId?: string) => {
  780. chatStore.updateCurrentSession(
  781. (session) =>
  782. (session.messages = session.messages.filter((m) => m.id !== msgId)),
  783. );
  784. };
  785. const onDelete = (msgId: string) => {
  786. deleteMessage(msgId);
  787. };
  788. const onResend = (message: ChatMessage) => {
  789. // when it is resending a message
  790. // 1. for a user's message, find the next bot response
  791. // 2. for a bot's message, find the last user's input
  792. // 3. delete original user input and bot's message
  793. // 4. resend the user's input
  794. const resendingIndex = session.messages.findIndex(
  795. (m) => m.id === message.id,
  796. );
  797. if (resendingIndex < 0 || resendingIndex >= session.messages.length) {
  798. console.error("[Chat] failed to find resending message", message);
  799. return;
  800. }
  801. let userMessage: ChatMessage | undefined;
  802. let botMessage: ChatMessage | undefined;
  803. if (message.role === "assistant") {
  804. // if it is resending a bot's message, find the user input for it
  805. botMessage = message;
  806. for (let i = resendingIndex; i >= 0; i -= 1) {
  807. if (session.messages[i].role === "user") {
  808. userMessage = session.messages[i];
  809. break;
  810. }
  811. }
  812. } else if (message.role === "user") {
  813. // if it is resending a user's input, find the bot's response
  814. userMessage = message;
  815. for (let i = resendingIndex; i < session.messages.length; i += 1) {
  816. if (session.messages[i].role === "assistant") {
  817. botMessage = session.messages[i];
  818. break;
  819. }
  820. }
  821. }
  822. if (userMessage === undefined) {
  823. console.error("[Chat] failed to resend", message);
  824. return;
  825. }
  826. // delete the original messages
  827. deleteMessage(userMessage.id);
  828. deleteMessage(botMessage?.id);
  829. // resend the message
  830. setIsLoading(true);
  831. const textContent = getMessageTextContent(userMessage);
  832. const images = getMessageImages(userMessage);
  833. chatStore.onUserInput(textContent, images).then(() => setIsLoading(false));
  834. inputRef.current?.focus();
  835. };
  836. const onPinMessage = (message: ChatMessage) => {
  837. chatStore.updateCurrentSession((session) =>
  838. session.mask.context.push(message),
  839. );
  840. showToast(Locale.Chat.Actions.PinToastContent, {
  841. text: Locale.Chat.Actions.PinToastAction,
  842. onClick: () => {
  843. setShowPromptModal(true);
  844. },
  845. });
  846. };
  847. const context: RenderMessage[] = useMemo(() => {
  848. return session.mask.hideContext ? [] : session.mask.context.slice();
  849. }, [session.mask.context, session.mask.hideContext]);
  850. const accessStore = useAccessStore();
  851. if (
  852. context.length === 0 &&
  853. session.messages.at(0)?.content !== BOT_HELLO.content
  854. ) {
  855. const copiedHello = Object.assign({}, BOT_HELLO);
  856. if (!accessStore.isAuthorized()) {
  857. copiedHello.content = Locale.Error.Unauthorized;
  858. }
  859. context.push(copiedHello);
  860. }
  861. // preview messages
  862. const renderMessages = useMemo(() => {
  863. return context
  864. .concat(session.messages as RenderMessage[])
  865. .concat(
  866. isLoading
  867. ? [
  868. {
  869. ...createMessage({
  870. role: "assistant",
  871. content: "……",
  872. }),
  873. preview: true,
  874. },
  875. ]
  876. : [],
  877. )
  878. .concat(
  879. userInput.length > 0 && config.sendPreviewBubble
  880. ? [
  881. {
  882. ...createMessage({
  883. role: "user",
  884. content: userInput,
  885. }),
  886. preview: true,
  887. },
  888. ]
  889. : [],
  890. );
  891. }, [
  892. config.sendPreviewBubble,
  893. context,
  894. isLoading,
  895. session.messages,
  896. userInput,
  897. ]);
  898. const [msgRenderIndex, _setMsgRenderIndex] = useState(
  899. Math.max(0, renderMessages.length - CHAT_PAGE_SIZE),
  900. );
  901. function setMsgRenderIndex(newIndex: number) {
  902. newIndex = Math.min(renderMessages.length - CHAT_PAGE_SIZE, newIndex);
  903. newIndex = Math.max(0, newIndex);
  904. _setMsgRenderIndex(newIndex);
  905. }
  906. const messages = useMemo(() => {
  907. const endRenderIndex = Math.min(
  908. msgRenderIndex + 3 * CHAT_PAGE_SIZE,
  909. renderMessages.length,
  910. );
  911. return renderMessages.slice(msgRenderIndex, endRenderIndex);
  912. }, [msgRenderIndex, renderMessages]);
  913. const onChatBodyScroll = (e: HTMLElement) => {
  914. const bottomHeight = e.scrollTop + e.clientHeight;
  915. const edgeThreshold = e.clientHeight;
  916. const isTouchTopEdge = e.scrollTop <= edgeThreshold;
  917. const isTouchBottomEdge = bottomHeight >= e.scrollHeight - edgeThreshold;
  918. const isHitBottom =
  919. bottomHeight >= e.scrollHeight - (isMobileScreen ? 4 : 10);
  920. const prevPageMsgIndex = msgRenderIndex - CHAT_PAGE_SIZE;
  921. const nextPageMsgIndex = msgRenderIndex + CHAT_PAGE_SIZE;
  922. if (isTouchTopEdge && !isTouchBottomEdge) {
  923. setMsgRenderIndex(prevPageMsgIndex);
  924. } else if (isTouchBottomEdge) {
  925. setMsgRenderIndex(nextPageMsgIndex);
  926. }
  927. setHitBottom(isHitBottom);
  928. setAutoScroll(isHitBottom);
  929. };
  930. function scrollToBottom() {
  931. setMsgRenderIndex(renderMessages.length - CHAT_PAGE_SIZE);
  932. scrollDomToBottom();
  933. }
  934. // clear context index = context length + index in messages
  935. const clearContextIndex =
  936. (session.clearContextIndex ?? -1) >= 0
  937. ? session.clearContextIndex! + context.length - msgRenderIndex
  938. : -1;
  939. const [showPromptModal, setShowPromptModal] = useState(false);
  940. const clientConfig = useMemo(() => getClientConfig(), []);
  941. const autoFocus = !isMobileScreen; // wont auto focus on mobile screen
  942. const showMaxIcon = !isMobileScreen && !clientConfig?.isApp;
  943. useCommand({
  944. fill: setUserInput,
  945. submit: (text) => {
  946. doSubmit(text);
  947. },
  948. code: (text) => {
  949. if (accessStore.disableFastLink) return;
  950. console.log("[Command] got code from url: ", text);
  951. showConfirm(Locale.URLCommand.Code + `code = ${text}`).then((res) => {
  952. if (res) {
  953. accessStore.update((access) => (access.accessCode = text));
  954. }
  955. });
  956. },
  957. settings: (text) => {
  958. if (accessStore.disableFastLink) return;
  959. try {
  960. const payload = JSON.parse(text) as {
  961. key?: string;
  962. url?: string;
  963. };
  964. console.log("[Command] got settings from url: ", payload);
  965. if (payload.key || payload.url) {
  966. showConfirm(
  967. Locale.URLCommand.Settings +
  968. `\n${JSON.stringify(payload, null, 4)}`,
  969. ).then((res) => {
  970. if (!res) return;
  971. if (payload.key) {
  972. accessStore.update(
  973. (access) => (access.openaiApiKey = payload.key!),
  974. );
  975. }
  976. if (payload.url) {
  977. accessStore.update((access) => (access.openaiUrl = payload.url!));
  978. }
  979. });
  980. }
  981. } catch {
  982. console.error("[Command] failed to get settings from url: ", text);
  983. }
  984. },
  985. });
  986. // edit / insert message modal
  987. const [isEditingMessage, setIsEditingMessage] = useState(false);
  988. // remember unfinished input
  989. useEffect(() => {
  990. // try to load from local storage
  991. const key = UNFINISHED_INPUT(session.id);
  992. const mayBeUnfinishedInput = localStorage.getItem(key);
  993. if (mayBeUnfinishedInput && userInput.length === 0) {
  994. setUserInput(mayBeUnfinishedInput);
  995. localStorage.removeItem(key);
  996. }
  997. const dom = inputRef.current;
  998. return () => {
  999. localStorage.setItem(key, dom?.value ?? "");
  1000. };
  1001. // eslint-disable-next-line react-hooks/exhaustive-deps
  1002. }, []);
  1003. const handlePaste = useCallback(
  1004. async (event: React.ClipboardEvent<HTMLTextAreaElement>) => {
  1005. const currentModel = chatStore.currentSession().mask.modelConfig.model;
  1006. if(!isVisionModel(currentModel)){return;}
  1007. const items = (event.clipboardData || window.clipboardData).items;
  1008. for (const item of items) {
  1009. if (item.kind === "file" && item.type.startsWith("image/")) {
  1010. event.preventDefault();
  1011. const file = item.getAsFile();
  1012. if (file) {
  1013. const images: string[] = [];
  1014. images.push(...attachImages);
  1015. images.push(
  1016. ...(await new Promise<string[]>((res, rej) => {
  1017. setUploading(true);
  1018. const imagesData: string[] = [];
  1019. compressImage(file, 256 * 1024)
  1020. .then((dataUrl) => {
  1021. imagesData.push(dataUrl);
  1022. setUploading(false);
  1023. res(imagesData);
  1024. })
  1025. .catch((e) => {
  1026. setUploading(false);
  1027. rej(e);
  1028. });
  1029. })),
  1030. );
  1031. const imagesLength = images.length;
  1032. if (imagesLength > 3) {
  1033. images.splice(3, imagesLength - 3);
  1034. }
  1035. setAttachImages(images);
  1036. }
  1037. }
  1038. }
  1039. },
  1040. [attachImages, chatStore],
  1041. );
  1042. async function uploadImage() {
  1043. const images: string[] = [];
  1044. images.push(...attachImages);
  1045. images.push(
  1046. ...(await new Promise<string[]>((res, rej) => {
  1047. const fileInput = document.createElement("input");
  1048. fileInput.type = "file";
  1049. fileInput.accept =
  1050. "image/png, image/jpeg, image/webp, image/heic, image/heif";
  1051. fileInput.multiple = true;
  1052. fileInput.onchange = (event: any) => {
  1053. setUploading(true);
  1054. const files = event.target.files;
  1055. const imagesData: string[] = [];
  1056. for (let i = 0; i < files.length; i++) {
  1057. const file = event.target.files[i];
  1058. compressImage(file, 256 * 1024)
  1059. .then((dataUrl) => {
  1060. imagesData.push(dataUrl);
  1061. if (
  1062. imagesData.length === 3 ||
  1063. imagesData.length === files.length
  1064. ) {
  1065. setUploading(false);
  1066. res(imagesData);
  1067. }
  1068. })
  1069. .catch((e) => {
  1070. setUploading(false);
  1071. rej(e);
  1072. });
  1073. }
  1074. };
  1075. fileInput.click();
  1076. })),
  1077. );
  1078. const imagesLength = images.length;
  1079. if (imagesLength > 3) {
  1080. images.splice(3, imagesLength - 3);
  1081. }
  1082. setAttachImages(images);
  1083. }
  1084. return (
  1085. <div className={styles.chat} key={session.id}>
  1086. <div className="window-header" data-tauri-drag-region>
  1087. {isMobileScreen && (
  1088. <div className="window-actions">
  1089. <div className={"window-action-button"}>
  1090. <IconButton
  1091. icon={<ReturnIcon />}
  1092. bordered
  1093. title={Locale.Chat.Actions.ChatList}
  1094. onClick={() => navigate(Path.Home)}
  1095. />
  1096. </div>
  1097. </div>
  1098. )}
  1099. <div className={`window-header-title ${styles["chat-body-title"]}`}>
  1100. <div
  1101. className={`window-header-main-title ${styles["chat-body-main-title"]}`}
  1102. onClickCapture={() => setIsEditingMessage(true)}
  1103. >
  1104. {!session.topic ? DEFAULT_TOPIC : session.topic}
  1105. </div>
  1106. <div className="window-header-sub-title">
  1107. {Locale.Chat.SubTitle(session.messages.length)}
  1108. </div>
  1109. </div>
  1110. <div className="window-actions">
  1111. {!isMobileScreen && (
  1112. <div className="window-action-button">
  1113. <IconButton
  1114. icon={<RenameIcon />}
  1115. bordered
  1116. onClick={() => setIsEditingMessage(true)}
  1117. />
  1118. </div>
  1119. )}
  1120. <div className="window-action-button">
  1121. <IconButton
  1122. icon={<ExportIcon />}
  1123. bordered
  1124. title={Locale.Chat.Actions.Export}
  1125. onClick={() => {
  1126. setShowExport(true);
  1127. }}
  1128. />
  1129. </div>
  1130. {showMaxIcon && (
  1131. <div className="window-action-button">
  1132. <IconButton
  1133. icon={config.tightBorder ? <MinIcon /> : <MaxIcon />}
  1134. bordered
  1135. onClick={() => {
  1136. config.update(
  1137. (config) => (config.tightBorder = !config.tightBorder),
  1138. );
  1139. }}
  1140. />
  1141. </div>
  1142. )}
  1143. </div>
  1144. <PromptToast
  1145. showToast={!hitBottom}
  1146. showModal={showPromptModal}
  1147. setShowModal={setShowPromptModal}
  1148. />
  1149. </div>
  1150. <div
  1151. className={styles["chat-body"]}
  1152. ref={scrollRef}
  1153. onScroll={(e) => onChatBodyScroll(e.currentTarget)}
  1154. onMouseDown={() => inputRef.current?.blur()}
  1155. onTouchStart={() => {
  1156. inputRef.current?.blur();
  1157. setAutoScroll(false);
  1158. }}
  1159. >
  1160. {messages.map((message, i) => {
  1161. const isUser = message.role === "user";
  1162. const isContext = i < context.length;
  1163. const showActions =
  1164. i > 0 &&
  1165. !(message.preview || message.content.length === 0) &&
  1166. !isContext;
  1167. const showTyping = message.preview || message.streaming;
  1168. const shouldShowClearContextDivider = i === clearContextIndex - 1;
  1169. return (
  1170. <Fragment key={message.id}>
  1171. <div
  1172. className={
  1173. isUser ? styles["chat-message-user"] : styles["chat-message"]
  1174. }
  1175. >
  1176. <div className={styles["chat-message-container"]}>
  1177. <div className={styles["chat-message-header"]}>
  1178. <div className={styles["chat-message-avatar"]}>
  1179. <div className={styles["chat-message-edit"]}>
  1180. <IconButton
  1181. icon={<EditIcon />}
  1182. onClick={async () => {
  1183. const newMessage = await showPrompt(
  1184. Locale.Chat.Actions.Edit,
  1185. getMessageTextContent(message),
  1186. 10,
  1187. );
  1188. let newContent: string | MultimodalContent[] =
  1189. newMessage;
  1190. const images = getMessageImages(message);
  1191. if (images.length > 0) {
  1192. newContent = [{ type: "text", text: newMessage }];
  1193. for (let i = 0; i < images.length; i++) {
  1194. newContent.push({
  1195. type: "image_url",
  1196. image_url: {
  1197. url: images[i],
  1198. },
  1199. });
  1200. }
  1201. }
  1202. chatStore.updateCurrentSession((session) => {
  1203. const m = session.mask.context
  1204. .concat(session.messages)
  1205. .find((m) => m.id === message.id);
  1206. if (m) {
  1207. m.content = newContent;
  1208. }
  1209. });
  1210. }}
  1211. ></IconButton>
  1212. </div>
  1213. {isUser ? (
  1214. <Avatar avatar={config.avatar} />
  1215. ) : (
  1216. <>
  1217. {["system"].includes(message.role) ? (
  1218. <Avatar avatar="2699-fe0f" />
  1219. ) : (
  1220. <MaskAvatar
  1221. avatar={session.mask.avatar}
  1222. model={
  1223. message.model || session.mask.modelConfig.model
  1224. }
  1225. />
  1226. )}
  1227. </>
  1228. )}
  1229. </div>
  1230. {showActions && (
  1231. <div className={styles["chat-message-actions"]}>
  1232. <div className={styles["chat-input-actions"]}>
  1233. {message.streaming ? (
  1234. <ChatAction
  1235. text={Locale.Chat.Actions.Stop}
  1236. icon={<StopIcon />}
  1237. onClick={() => onUserStop(message.id ?? i)}
  1238. />
  1239. ) : (
  1240. <>
  1241. <ChatAction
  1242. text={Locale.Chat.Actions.Retry}
  1243. icon={<ResetIcon />}
  1244. onClick={() => onResend(message)}
  1245. />
  1246. <ChatAction
  1247. text={Locale.Chat.Actions.Delete}
  1248. icon={<DeleteIcon />}
  1249. onClick={() => onDelete(message.id ?? i)}
  1250. />
  1251. <ChatAction
  1252. text={Locale.Chat.Actions.Pin}
  1253. icon={<PinIcon />}
  1254. onClick={() => onPinMessage(message)}
  1255. />
  1256. <ChatAction
  1257. text={Locale.Chat.Actions.Copy}
  1258. icon={<CopyIcon />}
  1259. onClick={() =>
  1260. copyToClipboard(
  1261. getMessageTextContent(message),
  1262. )
  1263. }
  1264. />
  1265. </>
  1266. )}
  1267. </div>
  1268. </div>
  1269. )}
  1270. </div>
  1271. {showTyping && (
  1272. <div className={styles["chat-message-status"]}>
  1273. {Locale.Chat.Typing}
  1274. </div>
  1275. )}
  1276. <div className={styles["chat-message-item"]}>
  1277. <Markdown
  1278. content={getMessageTextContent(message)}
  1279. loading={
  1280. (message.preview || message.streaming) &&
  1281. message.content.length === 0 &&
  1282. !isUser
  1283. }
  1284. onContextMenu={(e) => onRightClick(e, message)}
  1285. onDoubleClickCapture={() => {
  1286. if (!isMobileScreen) return;
  1287. setUserInput(getMessageTextContent(message));
  1288. }}
  1289. fontSize={fontSize}
  1290. parentRef={scrollRef}
  1291. defaultShow={i >= messages.length - 6}
  1292. />
  1293. {getMessageImages(message).length == 1 && (
  1294. <img
  1295. className={styles["chat-message-item-image"]}
  1296. src={getMessageImages(message)[0]}
  1297. alt=""
  1298. />
  1299. )}
  1300. {getMessageImages(message).length > 1 && (
  1301. <div
  1302. className={styles["chat-message-item-images"]}
  1303. style={
  1304. {
  1305. "--image-count": getMessageImages(message).length,
  1306. } as React.CSSProperties
  1307. }
  1308. >
  1309. {getMessageImages(message).map((image, index) => {
  1310. return (
  1311. <img
  1312. className={
  1313. styles["chat-message-item-image-multi"]
  1314. }
  1315. key={index}
  1316. src={image}
  1317. alt=""
  1318. />
  1319. );
  1320. })}
  1321. </div>
  1322. )}
  1323. </div>
  1324. <div className={styles["chat-message-action-date"]}>
  1325. {isContext
  1326. ? Locale.Chat.IsContext
  1327. : message.date.toLocaleString()}
  1328. </div>
  1329. </div>
  1330. </div>
  1331. {shouldShowClearContextDivider && <ClearContextDivider />}
  1332. </Fragment>
  1333. );
  1334. })}
  1335. </div>
  1336. <div className={styles["chat-input-panel"]}>
  1337. <PromptHints prompts={promptHints} onPromptSelect={onPromptSelect} />
  1338. <ChatActions
  1339. uploadImage={uploadImage}
  1340. setAttachImages={setAttachImages}
  1341. setUploading={setUploading}
  1342. showPromptModal={() => setShowPromptModal(true)}
  1343. scrollToBottom={scrollToBottom}
  1344. hitBottom={hitBottom}
  1345. uploading={uploading}
  1346. showPromptHints={() => {
  1347. // Click again to close
  1348. if (promptHints.length > 0) {
  1349. setPromptHints([]);
  1350. return;
  1351. }
  1352. inputRef.current?.focus();
  1353. setUserInput("/");
  1354. onSearch("");
  1355. }}
  1356. />
  1357. <label
  1358. className={`${styles["chat-input-panel-inner"]} ${
  1359. attachImages.length != 0
  1360. ? styles["chat-input-panel-inner-attach"]
  1361. : ""
  1362. }`}
  1363. htmlFor="chat-input"
  1364. >
  1365. <textarea
  1366. id="chat-input"
  1367. ref={inputRef}
  1368. className={styles["chat-input"]}
  1369. placeholder={Locale.Chat.Input(submitKey)}
  1370. onInput={(e) => onInput(e.currentTarget.value)}
  1371. value={userInput}
  1372. onKeyDown={onInputKeyDown}
  1373. onFocus={scrollToBottom}
  1374. onClick={scrollToBottom}
  1375. onPaste={handlePaste}
  1376. rows={inputRows}
  1377. autoFocus={autoFocus}
  1378. style={{
  1379. fontSize: config.fontSize,
  1380. }}
  1381. />
  1382. {attachImages.length != 0 && (
  1383. <div className={styles["attach-images"]}>
  1384. {attachImages.map((image, index) => {
  1385. return (
  1386. <div
  1387. key={index}
  1388. className={styles["attach-image"]}
  1389. style={{ backgroundImage: `url("${image}")` }}
  1390. >
  1391. <div className={styles["attach-image-mask"]}>
  1392. <DeleteImageButton
  1393. deleteImage={() => {
  1394. setAttachImages(
  1395. attachImages.filter((_, i) => i !== index),
  1396. );
  1397. }}
  1398. />
  1399. </div>
  1400. </div>
  1401. );
  1402. })}
  1403. </div>
  1404. )}
  1405. <IconButton
  1406. icon={<SendWhiteIcon />}
  1407. text={Locale.Chat.Send}
  1408. className={styles["chat-input-send"]}
  1409. type="primary"
  1410. onClick={() => doSubmit(userInput)}
  1411. />
  1412. </label>
  1413. </div>
  1414. {showExport && (
  1415. <ExportMessageModal onClose={() => setShowExport(false)} />
  1416. )}
  1417. {isEditingMessage && (
  1418. <EditMessageModal
  1419. onClose={() => {
  1420. setIsEditingMessage(false);
  1421. }}
  1422. />
  1423. )}
  1424. </div>
  1425. );
  1426. }
  1427. export function Chat() {
  1428. const chatStore = useChatStore();
  1429. const sessionIndex = chatStore.currentSessionIndex;
  1430. return <_Chat key={sessionIndex}></_Chat>;
  1431. }