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