chat.tsx 48 KB

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