chat.tsx 47 KB

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