chat.tsx 49 KB

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