chat.tsx 47 KB

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